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 |
---|---|---|---|---|---|---|---|---|---|---|---|
7287eca09651eb9dcfd85b902c3dc77011563d48
|
C++
|
utkarsh914/LeetCode
|
/Arrays and hashing/870. advantage-shuffle.cpp
|
UTF-8
| 1,686 | 3.5 | 4 |
[] |
no_license
|
// https://leetcode.com/problems/advantage-shuffle/
/*
Given two arrays A and B of equal size,
the advantage of A with respect to B is the number of indices i for which A[i] > B[i].
Return any permutation of A that maximizes its advantage with respect to B.
Example 1:
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]
*/
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& Bvec) {
vector<array<int,3>> B(Bvec.size());
for (int i=0; i < Bvec.size(); i++) {
B[i] = {Bvec[i], i, -1};
}
// sort A, B
sort(A.begin(), A.end());
sort(B.begin(), B.end());
vector<bool> taken(A.size(), false);
int i=A.size()-1, j=i;
while (i>=0 && j>=0) {
while (j >= 0 && A[i] <= B[j][0]) j--;
if (j < 0) break;
B[j][2] = A[i];
taken[i] = true;
i--, j--;
}
for (int i=0, j=0; i < taken.size(); i++) {
if (taken[i]) continue;
while (B[j][2] != -1) j++;
B[j][2] = A[i];
}
vector<int> ans(A.size());
for (auto& a : B) {
ans[a[1]] = a[2];
}
return ans;
}
};
/*
For each B[i], we select the smallest number in A that is greater than B[i].
If there are no such number, we select the smalest number in A.
I am usign multiset to sort and keep track of numbers in A.
After a number is selected, we need to remove it from the multiset
(erase by iterator takes a constant time).
*/
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
multiset<int> s(begin(A), end(A));
for (auto i = 0; i < B.size(); ++i) {
auto p = s.upper_bound(B[i]);
if(p == s.end()) p =s.begin();
A[i] = *p;
s.erase(p);
}
return A;
}
| true |
04a3547c302035dc8e7e8eb1d1eabfb1b9d536aa
|
C++
|
ssiloti/http
|
/uri/basic_uri.hpp
|
UTF-8
| 3,991 | 2.625 | 3 |
[
"BSL-1.0"
] |
permissive
|
#ifndef URI_BASIC_URI_HPP
#define URI_BASIC_URI_HPP
// Copyright 2009 Dean Michael Berris, Jeroen Habraken.
// Copyright 2011 Steven Siloti.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <uri/basic_authority.hpp>
namespace uri {
class invalid_uri : public std::exception
{
};
template <class String>
struct basic_uri
{
typedef String string_type;
basic_uri() {}
basic_uri(string_type const& uri);
basic_uri(const typename string_type::value_type* uri);
#if 0
basic_uri& operator=(basic_uri<string_type> other)
{
other.swap(*this);
return *this;
}
basic_uri& operator=(string_type const& uri)
{
return *this = basic_uri<string_type>(uri);
}
#endif
#if 0
void swap(basic_uri<string_type>& other)
{
using std::swap;
swap(other.parts_, parts_);
}
bool operator==(basic_uri<string_type> const& other) const
{
return scheme == other.scheme
&& authority == other.authority
&& path == other.path
&& query == other.query
&& fragment == other.fragment;
}
#endif
bool operator!=(basic_uri<string_type> const& other) const
{
return !(*this == other);
}
string_type scheme;
boost::optional<basic_authority<string_type> > authority;
string_type path;
boost::optional<string_type> query;
boost::optional<string_type> fragment;
};
namespace detail {
template <class String>
struct basic_uri_tuple
{
typedef String string_type;
typedef typename boost::fusion::tuple<
string_type&, // scheme
boost::fusion::tuple<
boost::optional<basic_authority<string_type> >&,
string_type& // path
>, // hier_part
boost::optional<string_type>&, // query
boost::optional<string_type>& // fragment
> type;
};
template <class String>
struct const_basic_uri_tuple
{
typedef String string_type;
typedef typename boost::fusion::tuple<
const string_type&, // scheme
const boost::optional<basic_authority<string_type> >&,
const string_type&, // path
const boost::optional<string_type>&, // query
const boost::optional<string_type>& // fragment
> type;
};
}
} // namespace uri
namespace boost { namespace spirit { namespace traits {
template <typename String>
struct transform_attribute<
uri::basic_uri<String>,
typename uri::detail::basic_uri_tuple<String>::type,
boost::spirit::qi::domain
>
{
typedef typename uri::detail::basic_uri_tuple<String>::type type;
static type pre(uri::basic_uri<String>& exposed) {
return type(
exposed.scheme,
boost::fusion::tie(
exposed.authority,
exposed.path
),
exposed.query,
exposed.fragment
);
}
static void post(uri::basic_uri<String>&, type const&) { }
static void fail(uri::basic_uri<String>& val) { }
};
template <typename String>
struct transform_attribute<
const uri::basic_uri<String>,
typename uri::detail::const_basic_uri_tuple<String>::type,
boost::spirit::karma::domain
>
{
typedef typename uri::detail::const_basic_uri_tuple<String>::type type;
static type pre(const uri::basic_uri<String>& exposed) {
return type(
exposed.scheme,
exposed.authority,
exposed.path,
exposed.query,
exposed.fragment
);
}
};
} // namespace traits
} // namespace spirit
} // namespace boost
#endif
| true |
2dc67db796b7c8177845c969b8bd61a20740c93b
|
C++
|
TylerMayxonesing/Uno
|
/Card.cpp
|
UTF-8
| 376 | 3 | 3 |
[] |
no_license
|
//
// Created by T Alpha 1 on 11/2/2019.
//
#include "Card.h"
Card::Card(std::string value, std::string color){
m_value = value;
m_color = color;
}
std::string Card::getValue(){
return m_value;
}
std::string Card::getColor(){
return m_color;
}
void Card::setValue(std::string value){
m_value = value;
}
void Card::setColor(std::string color){
m_value = color;
}
| true |
a449b724741bbcb039ad6d16d6937baaf47c0e09
|
C++
|
FrancoisSestier/fast_io
|
/helpers/bufsiz/iobuf.h
|
UTF-8
| 18,308 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
namespace fast_io
{
template<typename T,std::size_t alignment=4096>
struct io_aligned_allocator
{
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
[[nodiscard]] inline
#if __cpp_lib_is_constant_evaluated >= 201811L && __cpp_constexpr_dynamic_alloc >= 201907L
constexpr
#endif
T* allocate(std::size_t n)
{
#if __cpp_lib_is_constant_evaluated >= 201811L && __cpp_constexpr_dynamic_alloc >= 201907L
if(std::is_constant_evaluated())
return new T[n];
else
#endif
#if __cpp_sized_deallocation >= 201309L && __cpp_aligned_new >= 201606L
return static_cast<T*>(operator new(n*sizeof(T),std::align_val_t{alignment}));
#else
return new T[n];
#endif
}
inline
#if __cpp_lib_is_constant_evaluated >= 201811L && __cpp_constexpr_dynamic_alloc >= 201907L
constexpr
#endif
void deallocate(T* p, [[maybe_unused]] std::size_t n) noexcept
{
#if __cpp_lib_is_constant_evaluated >= 201811L && __cpp_constexpr_dynamic_alloc >= 201907L
if(std::is_constant_evaluated())
delete[] p;
else
#endif
#if __cpp_sized_deallocation >= 201309L && __cpp_aligned_new >= 201606L
operator delete(p,n*sizeof(T),std::align_val_t{alignment});
#else
delete[] p;
#endif
}
};
template<std::integral CharT,std::size_t buffer_size = ((
#if defined(__WINNT__) || defined(_MSC_VER)
1048576
#else
65536
#endif
<sizeof(CharT))?1:
#if defined(__WINNT__) || defined(_MSC_VER)
1048576
#else
65536
#endif
/sizeof(CharT)),typename Allocator = io_aligned_allocator<CharT>>
requires (buffer_size!=0)
class basic_buf_handler
{
Allocator alloc;
public:
using char_type = CharT;
using allocator_type = Allocator;
char_type *beg{},*curr{},*end{};
basic_buf_handler()=default;
basic_buf_handler& operator=(basic_buf_handler const&)=delete;
basic_buf_handler(basic_buf_handler const&)=delete;
static constexpr std::size_t size = buffer_size;
basic_buf_handler(basic_buf_handler&& m) noexcept:beg(m.beg),curr(m.curr),end(m.end)
{
m.end=m.curr=m.beg=nullptr;
}
basic_buf_handler& operator=(basic_buf_handler&& m) noexcept
{
if(std::addressof(m)!=this)[[likely]]
{
if(m.beg)
alloc.deallocate(beg,buffer_size);
beg=m.beg;
curr=m.curr;
end=m.end;
m.end=m.curr=m.beg=nullptr;
}
return *this;
}
inline void init_space()
{
end=curr=beg=alloc.allocate(buffer_size);
}
inline void release()
{
if(beg)[[likely]]
alloc.deallocate(beg,buffer_size);
end=curr=beg=nullptr;
}
~basic_buf_handler()
{
if(beg)[[likely]]
alloc.deallocate(beg,buffer_size);
}
Allocator get_allocator() const{ return alloc;}
};
template<input_stream Ihandler,typename Buf=basic_buf_handler<typename Ihandler::char_type>>
class basic_ibuf
{
public:
Ihandler ih;
Buf ibuffer;
using native_handle_type = Ihandler;
using buffer_type = Buf;
using char_type = typename Buf::char_type;
template<typename... Args>
requires std::constructible_from<Ihandler,Args...>
basic_ibuf(Args&&... args):ih(std::forward<Args>(args)...){}
inline constexpr auto& native_handle()
{
return ih;
}
};
template<input_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr bool underflow(basic_ibuf<Ihandler,Buf>& ib)
{
if(ib.ibuffer.end==nullptr)
ib.ibuffer.init_space();
ib.ibuffer.end=read(ib.ih,ib.ibuffer.beg,ib.ibuffer.beg+Buf::size);
ib.ibuffer.curr=ib.ibuffer.beg;
return ib.ibuffer.end!=ib.ibuffer.beg;
}
template<input_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr auto ibuffer_begin(basic_ibuf<Ihandler,Buf>& ib)
{
return ib.ibuffer.beg;
}
template<input_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr auto ibuffer_curr(basic_ibuf<Ihandler,Buf>& ib)
{
return ib.ibuffer.curr;
}
template<input_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr auto ibuffer_end(basic_ibuf<Ihandler,Buf>& ib)
{
return ib.ibuffer.end;
}
template<input_stream Ihandler,typename Buf>
inline constexpr void ibuffer_set_curr(basic_ibuf<Ihandler,Buf>& ib,typename Ihandler::char_type* ptr)
{
ib.ibuffer.curr=ptr;
}
template<buffer_output_stream Ihandler,typename Buf>
inline constexpr decltype(auto) overflow(basic_ibuf<Ihandler,Buf>& ib,typename Ihandler::char_type ch)
{
return overflow(ib.oh,ch);
}
template<buffer_output_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) obuffer_begin(basic_ibuf<Ihandler,Buf>& ib)
{
return obuffer_begin(ib.oh);
}
template<buffer_output_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) obuffer_curr(basic_ibuf<Ihandler,Buf>& ib)
{
return obuffer_curr(ib.oh);
}
template<buffer_output_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) obuffer_end(basic_ibuf<Ihandler,Buf>& ib)
{
return obuffer_end(ib.oh);
}
template<buffer_output_stream Ihandler,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) obuffer_set_curr(basic_ibuf<Ihandler,Buf>& ib,typename Ihandler::char_type* ptr)
{
return obuffer_set_curr(ib.oh,ptr);
}
template<output_stream Ihandler,typename Buf>
inline constexpr void flush(basic_ibuf<Ihandler,Buf>& ib)
{
flush(ib.native_handle());
}
template<output_stream Ihandler,typename Buf,std::contiguous_iterator Iter>
inline constexpr decltype(auto) write(basic_ibuf<Ihandler,Buf>& ib,Iter b,Iter e)
{
return write(ib.native_handle(),b,e);
}
template<redirect_stream Ihandler,typename Buf>
inline constexpr decltype(auto) redirect_handle(basic_ibuf<Ihandler,Buf>& ib)
{
return redirect_handle(ib.native_handle());
}
template<typename T,typename Iter>
concept write_read_punned_constraints = (std::contiguous_iterator<Iter>&&sizeof(typename T::char_type)==1) ||
(std::random_access_iterator<Iter>&&std::same_as<typename T::char_type,typename std::iterator_traits<Iter>::value_type>);
namespace details
{
template<std::size_t buffer_size,bool punning=false,typename T,typename Iter>
requires std::same_as<std::iter_value_t<Iter>,typename std::remove_cvref_t<T>::char_type>
inline constexpr Iter ibuf_read_cold(T& ib,Iter begin,Iter end)
{
std::size_t n(end-begin);
std::size_t const buffer_remain(ib.ibuffer.end-ib.ibuffer.curr);
if(ib.ibuffer.end==nullptr)
{
if(buffer_size<=n)
{
return read(ib.native_handle(),begin,end);
}
ib.ibuffer.init_space();
ib.ibuffer.curr=ib.ibuffer.end=ib.ibuffer.beg;
}
if constexpr(punning)
{
std::memcpy(begin,ib.ibuffer.curr,buffer_remain*sizeof(std::iter_value_t<Iter>));
begin+=buffer_remain;
}
else
begin=std::copy_n(ib.ibuffer.curr,buffer_remain,begin);
if(begin+buffer_size<end)
{
// if constexpr(std::contiguous_iterator<Iter>)
begin=read(ib.native_handle(),begin,end);
/* else
{
}*/
if(begin!=end)
{
ib.ibuffer.end=ib.ibuffer.curr=ib.ibuffer.beg;
return begin;
}
}
ib.ibuffer.end=read(ib.native_handle(),ib.ibuffer.beg,ib.ibuffer.beg+buffer_size);
ib.ibuffer.curr=ib.ibuffer.beg;
n=end-begin;
std::size_t const sz(ib.ibuffer.end-ib.ibuffer.beg);
if(sz<n)
n=sz;
if constexpr(punning)
{
std::memcpy(begin,ib.ibuffer.curr,n*sizeof(std::iter_value_t<Iter>));
begin+=n;
}
else
begin=std::copy_n(ib.ibuffer.curr,n,begin);
ib.ibuffer.curr+=n;
return begin;
}
template<std::size_t buffer_size,bool punning=false,typename T,typename Iter>
requires std::same_as<std::iter_value_t<Iter>,typename std::remove_cvref_t<T>::char_type>
inline constexpr Iter ibuf_read(T& ib,Iter begin,Iter end)
{
std::size_t n(end-begin);
if(ib.ibuffer.curr+n<ib.ibuffer.end)[[unlikely]] //cache miss
return ibuf_read_cold<buffer_size,punning>(ib,begin,end);
if constexpr(punning)
{
std::memcpy(begin,ib.ibuffer.curr,n*sizeof(std::iter_value_t<Iter>));
begin+=n;
}
else
begin=std::copy_n(ib.ibuffer.curr,n,begin);
ib.ibuffer.curr+=n;
return begin;
}
}
template<input_stream Ihandler,typename Buf,std::contiguous_iterator Iter>
requires (write_read_punned_constraints<basic_ibuf<Ihandler,Buf>,Iter>)
inline constexpr Iter read(basic_ibuf<Ihandler,Buf>& ib,Iter begin,Iter end)
{
using char_type = typename basic_ibuf<Ihandler,Buf>::char_type;
if constexpr(std::same_as<char_type,typename std::iterator_traits<Iter>::value_type>)
{
if(std::is_constant_evaluated())
return details::ibuf_read<Buf::size>(ib,std::to_address(begin),std::to_address(end));
else
return details::ibuf_read<Buf::size,true>(ib,std::to_address(begin),std::to_address(end));
}
else
{
auto b(reinterpret_cast<char const*>(std::to_address(begin)));
return begin+(details::ibuf_read<Buf::size,true>(ib,b,reinterpret_cast<char const*>(std::to_address(end)))-b)/sizeof(*begin);
}
}
template<input_stream Ihandler,typename Buf>
requires random_access_stream<Ihandler>
inline constexpr auto seek(basic_ibuf<Ihandler,Buf>& ib,std::common_type_t<std::ptrdiff_t,std::int64_t> u=0,seekdir s=seekdir::cur)
{
std::common_type_t<std::ptrdiff_t,std::int64_t> val(u-(ib.end-ib.curr)*sizeof(*ib.curr));
ib.ibuffer.curr=ib.ibuffer.end;
return seek(ib.native_handle(),val,s);
}
template<zero_copy_input_stream Ihandler,typename Buf>
inline constexpr decltype(auto) zero_copy_in_handle(basic_ibuf<Ihandler,Buf>& ib)
{
return zero_copy_in_handle(ib.native_handle());
}
template<zero_copy_output_stream Ohandler,typename Buf>
inline constexpr decltype(auto) zero_copy_out_handle(basic_ibuf<Ohandler,Buf>& ib)
{
return zero_copy_out_handle(ib.native_handle());
}
template<memory_map_input_stream Ihandler,typename Buf>
inline constexpr decltype(auto) memory_map_in_handle(basic_ibuf<Ihandler,Buf>& handle)
{
return memory_map_in_handle(handle.native_handle());
}
template<output_stream Ohandler,bool forcecopy=false,typename Buf=basic_buf_handler<typename Ohandler::char_type>>
class basic_obuf
{
public:
Ohandler oh;
Buf obuffer;
inline constexpr void close_impl() noexcept
{
#ifdef __cpp_exceptions
try
{
#endif
if(obuffer.beg)
write(oh,obuffer.beg,obuffer.curr);
#ifdef __cpp_exceptions
}
catch(...){}
#endif
}
public:
using native_handle_type = Ohandler;
using buffer_type = Buf;
using char_type = typename Buf::char_type;
template<typename... Args>
requires std::constructible_from<Ohandler,Args...>
basic_obuf(Args&&... args):oh(std::forward<Args>(args)...){}
~basic_obuf()
{
close_impl();
}
basic_obuf& operator=(basic_obuf const&)=delete;
basic_obuf(basic_obuf const&)=delete;
basic_obuf(basic_obuf&& bmv) noexcept:oh(std::move(bmv.oh)),obuffer(std::move(bmv.obuffer)){}
basic_obuf& operator=(basic_obuf&& b) noexcept
{
if(std::addressof(b)!=this)
{
close_impl();
oh=std::move(b.oh);
obuffer=std::move(b.obuffer);
}
return *this;
}
inline constexpr auto& native_handle()
{
return oh;
}
};
template<output_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr auto obuffer_begin(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ob.obuffer.beg;
}
template<output_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr auto& obuffer_curr(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ob.obuffer.curr;
}
template<output_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr auto obuffer_end(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ob.obuffer.end;
}
template<output_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr void obuffer_set_curr(basic_obuf<Ohandler,forcecopy,Buf>& ob,typename Ohandler::char_type* ptr)
{
ob.obuffer.curr=ptr;
}
template<output_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr void overflow(basic_obuf<Ohandler,forcecopy,Buf>& ob,typename Ohandler::char_type ch)
{
if(ob.obuffer.beg)
write(ob.native_handle(),ob.obuffer.beg,ob.obuffer.end);
else //cold buffer
{
ob.obuffer.init_space();
ob.obuffer.end=ob.obuffer.beg+Buf::size;
}
*(ob.obuffer.curr=ob.obuffer.beg)=ch;
++ob.obuffer.curr;
}
template<buffer_input_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) underflow(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return underflow(ob.oh);
}
template<buffer_input_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) ibuffer_begin(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ibuffer_begin(ob.oh);
}
template<buffer_input_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) ibuffer_curr(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ibuffer_curr(ob.oh);
}
template<buffer_input_stream Ohandler,bool forcecopy,typename Buf>
[[nodiscard]] inline constexpr decltype(auto) ibuffer_end(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return ibuffer_end(ob.oh);
}
template<buffer_input_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr decltype(auto) ibuffer_set_curr(basic_obuf<Ohandler,forcecopy,Buf>& ob,typename Ohandler::char_type* ptr)
{
return ibuffer_set_curr(ob.oh,ptr);
}
namespace details
{
template<bool punning=false,output_stream Ohandler,bool forcecopy,typename Buf,std::contiguous_iterator Iter>
constexpr void obuf_write_cold(basic_obuf<Ohandler,forcecopy,Buf>& ob,Iter cbegin,Iter cend,std::size_t diff)
{
if(ob.obuffer.end==nullptr) //cold buffer
{
if(T::buffer_type::size<=diff)
{
if constexpr(forcecopy&&!std::same_as<decltype(write(ob,begin,end)),void>)
{
auto it{write(ob.oh,begin,end)};
if(it!=end)
{
if(T::buffer_type::size<=end-it)
#ifdef __cpp_exceptions
throw posix_error(EIO);
#else
fast_terminate();
#endif
ob.obuffer.init_space();
ob.obuffer.end=(ob.obuffer.curr=ob.obuffer.beg)+T::buffer_type::size;
memcpy(ob.obuffer.beg,std::to_address(it),(end-it)*sizeof(*cbegin));
ob.obuffer.beg+=end-it;
}
}
else
{
write(ob.native_handle(),cbegin,cend);
}
return;
}
ob.obuffer.init_space();
ob.obuffer.end=(ob.obuffer.curr=ob.obuffer.beg)+T::buffer_type::size;
if constexpr(punning)
memcpy(ob.obuffer.curr,cbegin,diff*sizeof(std::iter_value_t<Iter>));
else
std::copy_n(cbegin,diff,ob.obuffer.curr);
ob.obuffer.curr+=diff;
return;
}
std::size_t n(ob.obuffer.end-ob.obuffer.curr);
if constexpr(punning)
memcpy(ob.obuffer.curr,cbegin,n*sizeof(std::iter_value_t<Iter>));
else
std::copy_n(cbegin,n,ob.obuffer.curr);
cbegin+=n;
if constexpr(forcecopy&&!std::same_as<decltype(write(ob,begin,end)),void>)
{
auto it{write(ob.native_handle(),ob.obuffer.beg,ob.obuffer.end)};
if(it!=end)
{
ob.obuffer.end=(ob.obuffer.curr=ob.obuffer.beg)+T::buffer_type::size;
memcpy(ob.obuffer.beg,std::to_address(it),(end-it)*sizeof(*cbegin));
ob.obuffer.beg+=end-it;
}
}
else
{
write(ob.native_handle(),ob.obuffer.beg,ob.obuffer.end);
if(cbegin+(T::buffer_type::size)<cend)
{
write(ob.oh,cbegin,cend);
ob.obuffer.curr=ob.obuffer.beg;
}
else
{
std::size_t const df(cend-cbegin);
if constexpr(punning)
memcpy(ob.obuffer.beg,cbegin,df*sizeof(std::iter_value_t<Iter>));
else
std::copy_n(cbegin,df,ob.obuffer.beg);
ob.obuffer.curr=ob.obuffer.beg+df;
}
}
}
template<bool punning=false,output_stream Ohandler,bool forcecopy,typename Buf,std::contiguous_iterator Iter>
requires std::same_as<std::iter_value_t<Iter>,typename std::remove_cvref_t<T>::char_type>
inline constexpr void obuf_write(basic_obuf<Ohandler,forcecopy,Buf>& ob,Iter cbegin,Iter cend)
{
std::size_t const diff(cend-cbegin);
auto curr{ob.obuffer.curr};
auto e{curr+diff};
if(e<=ob.obuffer.end)[[likely]]
{
if constexpr(punning)
memcpy(curr,cbegin,diff*sizeof(std::iter_value_t<Iter>));
else
std::copy_n(cbegin,diff,ob.obuffer.curr);
ob.obuffer.curr=e;
return;
}
obuf_write_cold<punning>(ob,cbegin,cend,diff);
}
}
template<output_stream Ohandler,bool forcecopy,typename Buf,std::contiguous_iterator Iter>
requires (write_read_punned_constraints<basic_obuf<Ohandler,forcecopy,Buf>,Iter>)
inline constexpr void write(basic_obuf<Ohandler,forcecopy,Buf>& ob,Iter cbegini,Iter cendi)
{
using char_type = typename basic_obuf<Ohandler,forcecopy,Buf>::char_type;
if constexpr(std::same_as<char_type,typename std::iterator_traits<Iter>::value_type>)
{
if(std::is_constant_evaluated())
details::obuf_write<false>(ob,std::to_address(cbegini),std::to_address(cendi));
else
details::obuf_write<true>(ob,std::to_address(cbegini),std::to_address(cendi));
}
else
details::obuf_write<true>(ob,reinterpret_cast<char const*>(std::to_address(cbegini)),
reinterpret_cast<char const*>(std::to_address(cendi)));
}
template<output_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr void flush(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
if(ob.obuffer.beg==ob.obuffer.curr)
return;
write(ob.native_handle(),ob.obuffer.beg,ob.obuffer.curr);
ob.obuffer.curr=ob.obuffer.beg;
// flush(oh.native_handle());
}
template<output_stream Ohandler,bool forcecopy,typename Buf,typename... Args>
requires random_access_stream<Ohandler>
inline constexpr decltype(auto) seek(basic_obuf<Ohandler,forcecopy,Buf>& ob,Args&& ...args)
{
if(ob.obuffer.beg!=ob.obuffer.curr)
{
write(ob.native_handle(),ob.obuffer.beg,ob.obuffer.curr);
ob.obuffer.curr=ob.obuffer.beg;
}
return seek(ob.native_handle(),std::forward<Args>(args)...);
}
template<input_stream Ohandler,typename Buf,std::contiguous_iterator Iter>
inline constexpr decltype(auto) read(basic_obuf<Ohandler,forcecopy,Buf>& ob,Iter begin,Iter end)
{
return read(ob.native_handle(),begin,end);
}
template<zero_copy_output_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr decltype(auto) zero_copy_out_handle(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return zero_copy_out_handle(ob.native_handle());
}
template<zero_copy_input_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr decltype(auto) zero_copy_in_handle(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return zero_copy_in_handle(ob.native_handle());
}
template<redirect_stream Ohandler,bool forcecopy,typename Buf>
inline constexpr decltype(auto) redirect_handle(basic_obuf<Ohandler,forcecopy,Buf>& ob)
{
return redirect_handle(ob.native_handle());
}
template<memory_map_input_stream Ihandler,typename Buf>
inline constexpr decltype(auto) memory_map_in_handle(basic_obuf<Ihandler,Buf>& handle)
{
return memory_map_in_handle(handle.native_handle());
}
template<io_stream ioh,bool forcecopy=false,typename bf=basic_buf_handler<typename ioh::char_type>>
using basic_iobuf=basic_obuf<basic_ibuf<ioh,bf>,forcecopy,bf>;
}
| true |
01275ed4271d2b728d9146bd6be1f088e03554b0
|
C++
|
mas1904/SimpleGameInSFML
|
/src/item.cpp
|
UTF-8
| 2,177 | 2.828125 | 3 |
[] |
no_license
|
#include "item.h"
item::item()
{
item::count=0;
build=false;
//ctor
}
item::item(sf::Sprite s){
}
item::~item()
{
//dtor
}
void item::set_count(short c){
item::count = c;
}
void item::setId(short c){
item::id = c;
}
void item::setHp(short c){
item::hp = c;
}
void item::setAD(short c){
item::attack = c;
}
void item::setDF(short c){
item::defense = c;
}
void item::setMaxHp(short c){
item::max_hp = c;
item::hp = c;
}
short item::getCount(){
return item::count;
}
short item::getId(){
return item::id;
}
short item::getHp(){
return item::hp;
}
short item::getAD(){
return item::attack;
}
short item::getDF(){
return item::defense;
}
short item::getMaxHp(){
return item::max_hp;
}
void item::setName(string n){
item::name = n;
}
string item::getName(){
return item::name;
}
bool item::isPickable(){
return item::pickable;
}
bool item::isThrowable(){
return item::throwable;
}
bool item::isCountable(){
return item::countable;
}
bool item::isBlockable(){
return item::blockable;
}
bool item::isBuild(){
return build;
}
short item::getDestroyItem(){
return destroyed;
}
short item::getBuildId(int orient){
return build_id[orient];
}
bool item::getBuildType(int orient){
return build_type[orient];
}
void item::setBuild(bool field[2], int id[2]){
for(int i=0;i<2;i++){
build_id[i] = id[i];
build_type[i] = field[i];
}
build=true;
}
short item::getType(){
return type;
}
void item::setType(bool c, bool p, bool t, bool b, short ad, short df, short destroyed, short type){
item::countable=c;
item::pickable=p;
item::throwable=t;
item::blockable=b;
item::attack=ad;
item::defense=df;
item::destroyed=destroyed;
item::type=type;
}
void item::addMine(std::vector<int> *l,std::vector<it_C> *cc){
chance=*l;
item::mines=*cc;
}
it_C item::mine(short hpm){
int liczba = std::rand()%100;
it_C tmp = {0,0};
for(int i=0;i<chance.size();i++){
if(liczba <= chance[i]){
tmp = mines[i];
break;
}
}
hp-=hpm*5;
return tmp;
}
| true |
9c36140148f576d2521fe415d1e18244ecbf6723
|
C++
|
xblunja/CubeMegaMod
|
/cwmods/cube/Item.h
|
UTF-8
| 1,037 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef ITEM_H
#define ITEM_H
#include "Spirit.h"
#include "../common/Vector2.h"
namespace cube {
class Creature;
class Item {
public:
char category;
//3 bytes padding
int id;
unsigned int modifier;
IntVector2 region;
char rarity;
//3 bytes padding
int formula_category;
char material;
cube::Spirit spirits[32];
char num_spirits;
//2 bytes padding
Item();
Item(char category, int id);
void ctor();
void Copy(cube::Item* src);
float GetArmor(cube::Creature* creature);
float GetHP(cube::Creature* creature);
int GetArtifactType();
int GetEffectiveRarity(IntVector2* region);
int GetPrice();
bool CanBeEquippedByClass(int classType);
bool IsPlusItem();
void ConvertToPlusItem();
void ConvertToNormalWeapon();
void UpgradeItem();
};
}
static_assert(sizeof(cube::Item) == 0xA0, "cube::Creature is not the correct size.");
#endif // ITEM_H
| true |
b3fda40d5ddde983c96fca69aa472b2864389747
|
C++
|
blegloannec/CodeProblems
|
/ACM-ICPC/Others/1113.cpp
|
UTF-8
| 2,652 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
// Trie + kinda Backtracking with memoization (kinda DP too)
typedef long long ll;
typedef vector<bool> morse_string;
/*
Binary Trie for morse words
terminal is the number of morse words of the dictionary
that end on the current node (we know there are no duplicates
in the original dictionary, but there might be some once
translated into morse code)
*/
struct MorseTree {
MorseTree *l,*r;
ll terminal;
MorseTree() {
l = NULL;
r = NULL;
terminal = 0;
}
void insert(const morse_string &s, unsigned int i);
void clear();
};
void MorseTree::insert(const morse_string &s, unsigned int i=0) {
if (i==s.size()) ++terminal;
else if (s[i]) {
if (r==NULL) r = new MorseTree();
r->insert(s,i+1);
}
else {
if (l==NULL) l = new MorseTree();
l->insert(s,i+1);
}
}
void MorseTree::clear() {
if (l!=NULL) l->clear();
if (r!=NULL) r->clear();
delete this;
}
morse_string L; // morse string to cut
MorseTree *LT; // Trie root
vector<ll> memo;
// kinda Backtracking + Memoization (only when on root node, i.e. actual cuts)
ll word_split(MorseTree *lt, unsigned int i=0) {
if (i==L.size()) return lt->terminal;
if (lt==LT && memo[i]>=0)
return memo[i];
ll res = 0;
// terminal node, possible cut here
if (lt->terminal>0) res += lt->terminal * word_split(LT,i);
// we try to continue, not cutting here
MorseTree *child = (L[i] ? lt->r : lt->l);
if (child!=NULL) res += word_split(child,i+1);
if (lt==LT) memo[i] = res;
return res;
}
// Morse code
vector<morse_string> M = {{0,1},{1,0,0,0},{1,0,1,0},{1,0,0},{0},{0,0,1,0},{1,1,0},{0,0,0,0},{0,0},{0,1,1,1},{1,0,1},{0,1,0,0},{1,1},{1,0},{1,1,1},{0,1,1,0},{1,1,0,1},{0,1,0},{0,0,0},{1},{0,0,1},{0,0,0,1},{0,1,1},{1,0,0,1},{1,0,1,1},{1,1,0,0}};
// Translate an english word into morse code
morse_string word2morse(const string &W) {
morse_string res;
for (unsigned int i=0; i<W.size(); ++i) {
int c = (int)W[i] - (int)'A';
for (morse_string::iterator it=M[c].begin(); it!=M[c].end(); ++it)
res.push_back(*it);
}
return res;
}
int main() {
int T;
cin >> T;
for (int t=0; t<T; ++t) {
string L0;
cin >> L0;
for (unsigned int i=0; i<L0.size(); ++i)
L.push_back(L0[i]=='-');
int N;
cin >> N;
LT = new MorseTree();
for (int i=0; i<N; ++i) {
string W;
cin >> W;
LT->insert(word2morse(W));
}
memo.resize(L.size(),-1);
if (t>0) cout << endl; // blank line
cout << word_split(LT) << endl;
// cleaning
L.clear();
LT->clear();
memo.clear();
}
return 0;
}
| true |
d1c54163e98e474c39cb7a0e89d745851edba151
|
C++
|
hs-krispy/BOJ
|
/Choose number.cpp
|
UTF-8
| 1,020 | 2.765625 | 3 |
[] |
no_license
|
//
// Created by 0864h on 2021-01-10.
//
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int N;
bool check[101], num_check[101];
vector<int> v[101], result, ans;
void choose(int start, int next)
{
if(!result.empty() && start == next)
{
for(int i = 0; i < result.size(); i++)
{
num_check[result[i]] = true;
ans.push_back(result[i]);
}
return;
}
if(!check[v[next][0]])
{
check[v[next][0]] = true;
result.push_back(v[next][0]);
choose(start, v[next][0]);
check[v[next][0]] = false;
result.pop_back();
}
}
int main()
{
cin >> N;
int num;
for(int i = 1; i <= N; i++)
{
cin >> num;
v[i].push_back(num);
}
for(int i = 1; i <= N; i++)
{
if(!num_check[i])
choose(i, i);
}
cout << ans.size() << "\n";
sort(ans.begin(), ans.end());
for(int i = 0; i < ans.size(); i++)
cout << ans[i] << "\n";
}
| true |
dd87af9e1bafde44a78922baffcfbbc9c94e96f8
|
C++
|
jrtokarz/QtStackedBar
|
/QStackedBar.hpp
|
UTF-8
| 1,116 | 2.53125 | 3 |
[] |
no_license
|
//
// Created by jrt on 9/7/19.
//
#ifndef QTSTACKEDBAR_QSTACKEDBAR_HPP
#define QTSTACKEDBAR_QSTACKEDBAR_HPP
#include <QtCore>
#include <QWidget>
#include <initializer_list>
class QStackedBar : public QWidget
{
Q_OBJECT
public:
struct Segment
{
int value;
QColor colour;
};
QStackedBar(unsigned int segements, QWidget *parent = nullptr);
void setSegments(unsigned int segments);
void setColor(const unsigned int segment, const QColor color);
void setMinimumValue(const int minVal);
void setMaximumValue(const int maxVal);
void setValues(const std::initializer_list<int>& list);
void mapToSegment(QObject* obj, unsigned int segment);
void setValue(unsigned int segment, int value);
public slots:
void setValue(const int value);
signals:
void valueChanged(const unsigned int segment, const int value);
protected:
void paintEvent(QPaintEvent* ev) override;
private:
QBrush m_brush{};
std::map<QObject*, unsigned int> m_objToSegment{};
std::vector<Segment> m_segments{};
};
#endif //QTSTACKEDBAR_QSTACKEDBAR_HPP
| true |
3bd53b48b9ec47de2a51c85c1fc97e285edebaf5
|
C++
|
Cloudxtreme/CyberBot
|
/src/cyber_logger.cpp
|
UTF-8
| 528 | 2.90625 | 3 |
[] |
no_license
|
#include "cyber_logger.h"
CyberLogger::CyberLogger(void){
filePath = "main_log.log";
fileOut.open(filePath, std::ios_base::app);
if(!fileOut.is_open()){
std::cout << "Error: could not open file for appending, creating a new one." << std::endl;
fileOut.open(filePath);
}
fileOut << "STARTED LOGGING\n";
}
CyberLogger::~CyberLogger(void){
fileOut << "ENDED LOGGING\n\n";
fileOut.close();
}
void CyberLogger::addMessage(std::string newMessage){
fileOut << newMessage + "\n";
std::cout << newMessage + "\n";
}
| true |
a5f33a2beb6c941dc72844dba76515519f387147
|
C++
|
rbx1219/cmaesXD
|
/FHH/gene.hpp
|
UTF-8
| 707 | 2.96875 | 3 |
[] |
no_license
|
#ifndef _gene_hpp
#define _gene_hpp
#include <iostream>
#include "random.hpp"
using namespace std;
class gene
{
public:
double Allele;
int code;
gene() {}
gene( const double v ) { Allele = v; }
gene( const gene &g ) { Allele = g.Allele; }
~gene() {}
void random();
double allele() { return Allele; }
gene & operator=(const gene &g);
gene & operator=(const double v );
int operator==(const gene &g) { return Allele == g.Allele; }
int operator==(const double v) { return Allele == v; }
int operator!=(const gene &g) { return Allele != g.Allele; }
int operator!=(const double v) { return Allele != v; }
friend ostream &operator<< (ostream &out, const gene &g);
};
#endif
| true |
82070ff066090bf3dffa3b70f0069b16df7acc8c
|
C++
|
christianyoedhana/CppPractice
|
/Learn Advanaced Modern C++/Logger/TextLogger.cpp
|
UTF-8
| 896 | 3.5 | 4 |
[] |
no_license
|
/*
Logger is a text logger.
User specifies the complete file path and name in the constructor.
Logger constructor must be non-converting and take a std::string
User enters the log using a function "log" that takes a std::string
Logger does not provide a timestamp entry. User is responsible for giving a complete string to save, including timestamps if necessary. This is to ensure that
the user can create a timestamped log entry as close as possible to the incident
"log" must be as lock-free as possible to the caller of log
*/
#include "TextLogger.h"
#include <chrono>
using namespace std;
//Text file output only
TextLogger::TextLogger(const string& fileName) : m_file{ fileName } {}
void TextLogger::log(const string& entry) {
m_file << entry;
}
string TextLogger::createTimestampedEntry(const string& entry) {
return string{ string{"Time to be implemented"} + string{" "} + entry };
}
| true |
8d1ae115db707dd9f21f75422306683e8dc34c1a
|
C++
|
Shung-2/Scott_Pilgrim
|
/MapManager.cpp
|
UTF-8
| 1,562 | 2.78125 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "MapManager.h"
HRESULT MapManager::Init()
{
sinkholeStartX = 2940;
sinkholeEndX = 3340;
sinkholeStartZ = 380;
sinkholeEndZ = 568;
slopeStartX1 = 16920;
slopeEndX1 = 17240;
slopeStartZ1 = 380;
slopeEndZ1 = 800;
slopeStartX2 = 18900;
slopeEndX2 = 19175;
slopeStartZ2 = 380;
slopeEndZ2 = 600;
slopeAngle1 = PI / 3;
return S_OK;
}
void MapManager::Update()
{
for (int i = 0; i < enemyV->size(); i++)
{
if ((*enemyV)[i]->transform->GetX() >= sinkholeStartX &&
(*enemyV)[i]->transform->GetX() <= sinkholeEndX &&
(*enemyV)[i]->GetComponent<ZOrder>()->GetZ() >= sinkholeStartZ &&
(*enemyV)[i]->GetComponent<ZOrder>()->GetZ() <= sinkholeEndZ)
{
(*enemyV)[i]->GetComponent<ZOrder>()->SetZ(1000);
}
}
if (player->transform->GetX() >= sinkholeStartX &&
player->transform->GetX() <= sinkholeEndX &&
player->GetComponent<ZOrder>()->GetZ() >= sinkholeStartZ &&
player->GetComponent<ZOrder>()->GetZ() <= sinkholeEndZ)
{
player->GetComponent<ZOrder>()->SetZ(1000);
}
}
void MapManager::Release()
{
}
bool MapManager::IsInSlope1(GameObject* gameObject)
{
if (gameObject->transform->GetX() >= slopeStartX1 &&
gameObject->transform->GetX() <= slopeEndX1 &&
gameObject->GetComponent<ZOrder>()->GetZ() >= slopeStartZ1 &&
gameObject->GetComponent<ZOrder>()->GetZ() <= slopeEndZ1)
{
return true;
}
return false;
}
| true |
a7e8ba5e417df65346a375257e048efc4168fbc7
|
C++
|
Ciamek/SDiZO_1
|
/Lista.cpp
|
UTF-8
| 3,851 | 3.671875 | 4 |
[] |
no_license
|
//
// Created by Maciej Ciura on 14.03.2020.
//
#include<iostream>
#include "Lista.h"
using namespace std;
Lista::Lista() {
head = nullptr;
tail = nullptr;
size = 0;
}
Lista::~Lista() {
for (int i=0; i<size; i++)
{
ListEl *temp = head->next;
delete head;
head=temp;
}
}
void Lista::pushFront(int value) {
if(head == nullptr)
{
head = new ListEl();
head->data = value;
tail = head;
}
else
{
auto *newHead = new ListEl();
newHead->data = value;
newHead->next = head;
newHead->prev = nullptr;
head->prev = newHead;
head = newHead;
}
size++;
}
void Lista::pushBack(int value) {
if(head == nullptr)
{
head = new ListEl();
tail = head;
}
else
{
auto *newTail = new ListEl;
newTail->data = value;
newTail->prev = tail;
newTail->next = nullptr;
tail->next = newTail;
tail = newTail;
}
size++;
}
void Lista::popFront() {
if (size > 1) {
head->next->prev= nullptr;
head = head->next;
} else {
head = nullptr;
tail = nullptr;
}
size--;
}
void Lista::popBack() {
if (size > 1) {
tail->prev->next= nullptr;
tail = tail-> prev;
} else {
head = nullptr;
tail = nullptr;
}
size--;
}
void Lista::pushAny(int value, int pos) {
if(pos < 0 || pos > size)
{
std::cout<<"Nie ma takiego indeksu!";
return;
}
if(pos == 0)
{
this->pushFront(value);
return;
}
if(pos == size)
{
this->pushBack(value);
return;
}
ListEl *temp;
if(pos < size /2)
{
temp = head;
for(int i=0; i < pos; i++)
{
temp = temp->next;
}
} else
{
temp = tail;
for(int i= 0 ; i < getSize() - pos - 1; i++)
{
temp = temp->prev;
}
}
auto *newElem = new ListEl();
newElem->next = temp;
newElem->prev = temp->prev;
newElem->data = value;
temp->prev->next = newElem;
temp->prev = newElem;
}
void Lista::popAny(int pos) {
if(pos < 0 || pos >= size)
{
std::cout<<"Nie ma takiego indeksu!";
return;
}
if(pos == 0)
{
this->popFront();
return;
}
if(pos == size-1)
{
this->popBack();
return;
}
ListEl * temp;
if(pos < size /2)
{
temp = head;
for(int i=0; i < pos; i++)
temp = temp->next;
} else
{
temp = tail;
for(int i=0; i < getSize() - pos - 1; i++)
temp = temp->prev;
}
temp->next->prev = temp->prev;
temp->prev->next = temp->next;
size--;
}
int Lista::getSize()
{
return this->size;
}
int Lista::checkIfPresent(int value) {
//Jeżeli lista jest pusta, zwróć false z automatu
if (size == 0) {
return -1;
}
ListEl *newHead;
//Przypisa pierwszy element jako aktualny
newHead = head;
//Przeszukaj listę pod kątem wartości
for (int i = 0; i < size; i++) {
if (newHead->data == value) {
return i;
}
newHead = newHead->next;
}
//Jeżeli wartość nie wystąpiła w żadnej iteracji listy zwróć false
return -1;
}
void Lista::print() {
//Ustaw jako akutualny element pierwszy element listy
cout << "Aktualny stan listy:" << endl;
ListEl *newHead = head;
if (size == 0)
cout << "Lista nie zawiera zadnego elementu." << endl;
for (int i = 0; i < size; i++) {
cout << "{" << newHead->data << "} ";
//Przypisz kolejny element listy jako aktualny
newHead = newHead->next;
}
}
| true |
cdbd9e7267719804b7f3512ad2ba5e1cdebebef8
|
C++
|
Atsushi4/qtngy_examples
|
/Threading/threadnewmanager.cpp
|
UTF-8
| 1,830 | 2.734375 | 3 |
[] |
no_license
|
#include "threadnewmanager.h"
#include <QThread>
#include <QDebug>
class ThreadNewManager::CustomThread : public QThread
{
Q_OBJECT
public:
explicit CustomThread(QObject *parent) : QThread(parent) {}
const QList<Worker*> &workers() {return workers_;}
void go() {emit startWork();}
signals:
void startWork();
void stopWork();
private:
void run() {
for (int i = 0; i < Manager::WorkerCount; ++i) {
auto w = new Worker();
connect(this, SIGNAL(startWork()), w, SLOT(doWork()));
connect(this, SIGNAL(stopWork()), w, SLOT(stop()));
connect(this, SIGNAL(finished()), w, SLOT(deleteLater()));
workers_ << w;
}
exec();
}
QList<Worker*> workers_;
};
ThreadNewManager::ThreadNewManager(QObject *parent) :
Manager(parent)
{
for (int i = 0; i < ThreadCount; ++i) {
auto t = new CustomThread(this);
connect(this, SIGNAL(pauseWorker()), t, SIGNAL(stopWork()));
t->start();
threads_ << t;
}
}
ThreadNewManager::~ThreadNewManager()
{
for (auto t : threads_) {
t->quit();
t->wait();
}
}
void ThreadNewManager::run(Manager::RunMode mode)
{
// シグナルのマッピング
if (mode == RunSeries) {
for (int i = 0; i < WorkerCount; ++i) {
connect(threads_.at(0)->workers().at(i), SIGNAL(progressChanged(int)), workers().at(i), SIGNAL(progressChanged(int)));
}
threads_.at(0)->go();
} else {
for (int i = 0; i < WorkerCount; ++i)
connect(threads_.at(i % ThreadCount)->workers().at(i), SIGNAL(progressChanged(int)), workers().at(i), SIGNAL(progressChanged(int)));
for (int i = 0; i < ThreadCount; ++i)
threads_.at(i)->go();
}
}
#include "threadnewmanager.moc"
| true |
22ec305e22e638124b71ecb76c22103972b1a027
|
C++
|
RaykoEZ/PPP_Asteroids
|
/PPP_Assteroids_Proj/include/GameObjects.h
|
UTF-8
| 4,718 | 3.125 | 3 |
[] |
no_license
|
#ifndef GAMEOBJECTS_H
#define GAMEOBJECTS_H
#include <cmath>
#ifdef WIN32
#include <Windows.h> // must be before gl.h include
#endif
#if defined (__linux__) || defined (WIN32)
#include <GL/gl.h>
#endif
#ifdef __APPLE__
#include <OpenGL/gl.h>
#endif
#include "Vec4.h"
///\file GameObjects.h
/// \author Chengyan Zhang (Eric)
/// \version 1.0
/// \date Last Revision 06/05/2017 \n
/// Revision History : \n
/// \class GameObjects
/// \brief Class for defining a GameObject in general
/// \todo None yet.
///\brief For conversion into degrees
float degree();
///\brief For conversion into radians
float radian();
///\brief For drawing a generic ship
/// @param[in] _size - size modifier
void shipType(const float _size);
///\brief For drawing a generic bullet
/// @param[in] _size - size modifier
void bulletType(const float _size);
///\brief For drawing a generic asteroid
/// @param[in] _size - size modifier
void asteroidType(const float _size);
/// \class GameObjects
/// \brief Class for Storing general methods allowing all GameObjects to move and have basic interactions.
/// \todo None yet.
class GameObjects
{
public:
///\brief Function pointer for types of things we draw
/// @param[in] _size - size modifier
typedef void (*Shape)(const float _size);
///\brief The type of objects defines which function we use to draw
Shape m_shapeType;
///\brief position of object in vector form
Vec4 m_position;
///\brief direction of object in vector form
Vec4 m_direction;
///\brief current velocity
float m_velocity;
///\brief For drawing objects on screen
/// @param[in] _type - type of object we are drawing calls different glBegin() functions
/// @param[in] _x - x displacement
/// @param[in] _y - y displacement
/// @param[in] _rot - rotation in degrees
void drawMe(Shape _type,float &_x,float &_y, float _rot);
///\brief For modifying direction vector when rotating
/// @param[in] _left - whether we are roting anti-clockwise
/// @param[in] _rotDeg - angle size for each rotation
void rotateMe(bool _left,float _rotDeg);
///\brief For calling update function
/// @param[in] _type - the type of object we are drawing calls different glBegin() functions
void forward(Shape _type);
///\brief For modifying the position vector for movement
/// @param[in] _step - interval for each move
void move(float &_step);
///\brief For getting the size for this object
float getSize()const{return m_size;}
///\brief default ctor for our player's ship
GameObjects():
m_size(0.75f),
m_shapeType(shipType),
m_velocity(0.0f),
m_rot(0.0f),
m_rotSpd(7.5f),
m_position(0.0f,0.0f,0.0f,1.0f),
m_direction(0.0f,1.0f,0.0f,1.0f){;}
///\brief ctor for bulllets
/// @param[in] _v - speed of this object
/// @param[in] _size - size modifier
/// @param[in] _type - type of object we should be drawing for this object
/// @param[in] _dir - direction vector
/// @param[in] _pos - position vector
GameObjects(float _v,float _size ,Shape _type,Vec4 _dir, Vec4 _pos):
m_size(_size),
m_shapeType(_type),
m_velocity(_v),
m_rot(0.0f),
m_rotSpd(0.0f),
m_position(_pos),
m_direction(_dir){;}
///\brief ctor for asteroids
/// @param[in] _dir - direction vector
/// @param[in] _pos - position vector
/// @param[in] _v - speed of this object
/// @param[in] _rot - rotation in degrees
/// @param[in] _rotSpd - rotation speed of this object
/// @param[in] _size - size modifier
/// @param[in] _type - type of object we should be drawing for this object
GameObjects(Vec4 _dir,Vec4 _pos, float _v, float _rot, float _rotSpd, float _size, Shape _type):
m_direction(_dir),
m_position(_pos),
m_velocity(_v),
m_rot(_rot),
m_rotSpd(_rotSpd),
m_size(_size),
m_shapeType(_type){;}
virtual ~GameObjects(){;}
protected:
///\brief size modifier
float m_size;
///\brief current angle of rotation in degrees
float m_rot;
///\brief rotation speed
float m_rotSpd;
///\brief For cycling rotation angle when a full turn is made
void cycle();
///\brief For returning objects back into the view volume when they are out of the screen
void outOfScreen();
///\brief maximum position this object can go off the screen;
float m_clipLimit=20.0f;
};
#endif // GAMEOBJECTS_H
| true |
f9c8dfde047260754ad61a1432b26bb741a08214
|
C++
|
sogapalag/contest
|
/hackerrank/hourrank-21/c.cpp
|
UTF-8
| 3,847 | 2.578125 | 3 |
[] |
no_license
|
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define DEBUGP(val) cerr << #val << "=" << val << "\n"
using namespace std;
typedef long long int ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> PI;
const ll mod = 1e9 + 7;
/*
* Dependencies: typedef long long ll
* Headers: iostream
* Verified by: ARC099-F
* https://beta.atcoder.jp/contests/arc099/submissions/2743855
*/
template<ll mod = (ll)1e9 + 7>
struct ModInt {
ll x;
ModInt(void): x(0) {}
ModInt(ll x): x(x % mod){}
ModInt(const ModInt &x): x(x.x) {}
ModInt operator+(ModInt o) const {
ll y = x + o.x;
if (y >= mod) y -= mod;
return ModInt(y);
}
ModInt operator-(ModInt o) const {
ll y = x - o.x + mod;
if (y >= mod) y -= mod;
return ModInt(y);
}
ModInt operator*(ModInt o) const {
return ModInt((x * o.x) % mod);
}
void operator+=(ModInt o) { *this = *this + o; }
void operator-=(ModInt o) { *this = *this - o; }
void operator*=(ModInt o) { *this = *this * o; }
ModInt operator-(void) const { return ModInt() - *this; }
ll to_ll() const {
return x;
}
bool operator<(ModInt o) const {
return x < o.x;
}
ModInt pow(ll e) {
assert (e >= 0);
ModInt sum = 1;
ModInt cur = *this;
while (e > 0) {
if (e % 2) {
sum = sum * cur;
}
cur = cur * cur;
e /= 2;
}
return sum;
}
ModInt inv(void) {
return pow(mod - 2);
}
};
template<ll mod>
ostream &operator<<(ostream &os, ModInt<mod> mi) {
return os << mi.x;
}
/*
* Union-Find tree
* header requirement: vector
*/
class UnionFind {
private:
std::vector<int> disj;
std::vector<int> rank;
public:
UnionFind(int n) : disj(n), rank(n) {
for (int i = 0; i < n; ++i) {
disj[i] = i;
rank[i] = 0;
}
}
int root(int x) {
if (disj[x] == x) {
return x;
}
return disj[x] = root(disj[x]);
}
void unite(int x, int y) {
x = root(x);
y = root(y);
if (x == y) {
return;
}
if (rank[x] < rank[y]) {
disj[x] = y;
} else {
disj[y] = x;
if (rank[x] == rank[y]) {
++rank[x];
}
}
}
bool is_same_set(int x, int y) {
return root(x) == root(y);
}
};
const int N = 19;
VI g[N];
const int B = 2;
int b[B] = {17, 251};
vector<ModInt<> > calc(int bits, int v, int p) {
vector<ModInt<> > ret(B, 1);
for (int w: g[v]) {
if (p == w) continue;
if ((bits & 1 << w) == 0) continue;
vector<ModInt<> > sub = calc(bits, w, v);
REP(i, 0, B) {
ret[i] += sub[i] * sub[i] * b[i];
}
}
return ret;
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
REP(i, 0, n - 1) {
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
g[b].push_back(a);
}
set<vector<ModInt<> > > occ;
REP(bits, 0, 1 << n) {
UnionFind uf(n);
REP(i, 0, n) {
if (bits & 1 << i) {
for (int j: g[i]) {
if (bits & 1 << j) uf.unite(i, j);
}
}
}
set<int> conn;
REP(i, 0, n) {
if (bits & 1 << i) {
conn.insert(uf.root(i));
if (conn.size() >= 2) break;
}
}
if (conn.size() >= 2) continue;
// bits forms a subtree.
vector<ModInt<> > hash(B, 1);
REP(i, 0, n) {
if (bits & 1 << i) {
vector<ModInt<> > sub = calc(bits, i, -1);
REP(j, 0, B) hash[j] *= sub[j];
}
}
occ.insert(hash);
}
cout << occ.size() << endl;
}
| true |
8799c7188e0cfc69918ce1bba13f55b42766e93c
|
C++
|
ChoiCheoulWon/BasicEngineeringDesign
|
/BasicEngineeringDesign/Project_1/project_1.cpp
|
UHC
| 2,963 | 3.875 | 4 |
[] |
no_license
|
/*
Ʈ1
Էµ Ģ ϴ α
ڸ ڸ Էµȴٰ
Ҽ ° ڸ
ϴ ִٰ
ʱⰪ = 0
ڿ
ڰ Ŀ '.' Է ݺϿ Է¹´.
'.' ԷµǸ α
䱸
ڡ Է ´.
ȯ gcc Ѵ
0 Էµ Ѵ
ڸ Է ϴ
Ҽ ° ڸ ϳ.
Ģ ݵ Լ ̿Ͽ ´.
ϴ Լ ݵ call by reference Ѵ.
ݺ Ѵ.
*/
#include <iostream>
using namespace std;
double add(char, char);
double sub(char, char);
double mul(char, char);
double div(char, char);
void add_mem(double*, double*);
int main() {
char a, op, b;
double nusan = 0, result;
int ans,div0_flag;
while (1) {
cout << " Էϼ : ";
cin >> a;
if (a == '.') {
cout << fixed;
cout.precision(2);
cout << " : " << nusan << endl;
break;
}
cin >> op;
cin >> b;
div0_flag = 0;
if (op == '+') result = add(a, b);
if (op == '-') result = sub(a, b);
if (op == '*') result = mul(a, b);
if (op == '/') {
if (b == '0') {
cout << "0 ϴ." << endl;
div0_flag = 1;
}
else
result = div(a, b);
}
if (div0_flag != 1) {
cout << fixed;
cout.precision(2);
cout << " : " << result << endl;
cout << " ұ?" << endl;
cout << "1. 2. ƴϿ : "; cin >> ans;
if (ans == 1) add_mem(&nusan, &result);
cout << fixed;
cout.precision(2);
cout << " : " << nusan << endl;
}
}
}
double add(char a, char b) {
double num_a, num_b;
num_a = (double)(a - '0');
num_b = (double)(b - '0');
return num_a + num_b;
}
double sub(char a, char b) {
double num_a, num_b;
num_a = (double)(a - '0');
;
num_b = (double)(b - '0');
return num_a - num_b;
}
double mul(char a, char b) {
double num_a, num_b;
num_a = (double)(a - '0');
num_b = (double)(b - '0');
return num_a * num_b;
}
double div(char a, char b) {
double num_a, num_b;
num_a = (double)(a - '0');
num_b = (double)(b - '0');
return num_a / num_b;
}
void add_mem(double* nusan, double* result) {
*nusan += *result;
}
| true |
9e81aef344f7c43f298fabcc9faf7f2e8fd0f5a9
|
C++
|
mokerjoke/Halide
|
/cpp/src/Reduction.h
|
UTF-8
| 882 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef HALIDE_REDUCTION_H
#define HALIDE_REDUCTION_H
#include "IntrusivePtr.h"
namespace Halide {
namespace Internal {
struct ReductionVariable {
std::string var;
Expr min, extent;
};
struct ReductionDomainContents {
mutable RefCount ref_count;
vector<ReductionVariable> domain;
};
class ReductionDomain {
IntrusivePtr<ReductionDomainContents> contents;
public:
ReductionDomain() : contents(NULL) {}
ReductionDomain(const vector<ReductionVariable> &domain) :
contents(new ReductionDomainContents) {
contents.ptr->domain = domain;
}
bool defined() const {
return contents.defined();
}
bool same_as(const ReductionDomain &other) const {
return contents.same_as(other.contents);
}
const vector<ReductionVariable> &domain() const {
return contents.ptr->domain;
}
};
}
}
#endif
| true |
dbbdf7b3331a66cdaeb13e044eb00b9f05845a7b
|
C++
|
dzwduan/cpp-prog-lang-ex
|
/9_Statements/Ex/2/Source.cpp
|
UTF-8
| 525 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
/*
[2] (∗1) See how your compiler reacts to these errors:
void f(int a, int b)
{
if (a = 3) // ...
if (a&077 == 0) // ...
a := b+1;
}
Devise more simple errors and see how the compiler reacts.
*/
#include <iostream>
void f(int a, int b)
{
if (a = 3) std::cout << __LINE__ << "\n"; // no warning
//if (a & 077 == 0) std::cout << __LINE__ << "\n"; // Warning C4554 '&': check operator precedence for possible error; use parentheses to clarify precedence
//a := b + 1; // syntax error
}
int main()
{
f(1, 2);
}
| true |
c67699bc293630a0e31849c463c2dc0f93f87019
|
C++
|
maobing/AlgorithmsInCpp
|
/exponentialMA.cpp
|
UTF-8
| 946 | 3.640625 | 4 |
[] |
no_license
|
// exponential moving average
// S_t = a * Y_t + (1-a) * S_t-1
#include<vector>
#include<iostream>
using namespace std;
class Solution{
public:
Solution(): n(5) {}
void expMA(const vector<double> &data) {
if (data.size() == 0) return;
alpha = 1.0/data.size();
movingAverage.push_back(data[0]);
for(vector<double>::const_iterator a = data.begin() + 1; a != data.end(); a++) {
movingAverage.push_back(alpha * (*a) + (1 - alpha) * movingAverage.back());
}
return;
}
const vector<double>& getMA() {
return movingAverage;
}
private:
vector<double> movingAverage;
size_t n;
double alpha;
};
int main() {
Solution solution;
vector<double> data{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
solution.expMA(data);
vector<double> myMA = solution.getMA();
for(vector<double>::iterator a = myMA.begin(); a != myMA.end(); a++) {
cout << *a << endl;
}
}
| true |
a258d84b286e6658ed5e248f4a5686abf6e2fcff
|
C++
|
OC-MCS/prog4-mortgage-01-DylanF967
|
/Prog4-Mortgage/main.cpp
|
UTF-8
| 1,703 | 3.609375 | 4 |
[] |
no_license
|
//Dylan Fortney
// Programming 2
// Mortgage
#include <iostream>
#include "Mortgage.h"
#include <string>
#include <iomanip>
using namespace std;
//This calls all the member functions and gets the needed values from them and it asks the user for the needed starting info
//such as the interest on the loan and the number of years they have been paying the loan.
//Well I thought the to_string would fix the issue I was having but if I put in anything but a number it just crashes
//So again I'm unsure how to fix this issue.
int main()
{
Mortgage House;
double Year;
double Interest;
double Loan;
double Payment;
double Term;
double TotalPaid;
cout << "What is the interest on this loan?" << endl;
cin >> Interest;
//This is what I thought would check to make sure the value was a number before going on to the next cin.
//However the program doesn't reach this point instead it just crashes as soon as the cin gets anything but a number.
string Interest_s;
Interest_s = to_string(Interest);
while (!isdigit(Interest_s [0]))
{
cout << "Please input a valid number." << endl;
cin >> Interest;
}
cout << "What is the number of years you've been paying this loan?" << endl;
cin >> Year;
cout << "What is the Loan itself?" << endl;
cin >> Loan;
House.setInterest(Interest);
House.setLoan(Loan);
House.setYear(Year);
Term = House.FindTerm(Interest, Year);
House.setInterest(Term);
cout << "This is the amount you must pay every month: $" << fixed << showpoint << setprecision(2) << House.FindPayment() << endl;
cout << "This is the total amount you will have paid by the end of the year: $" << fixed << showpoint << setprecision(2) << House.FindTotal();
}
| true |
fc415de5d27581a4d887f74d441c8e182a98167a
|
C++
|
TrueAstralpirate/3DRenderer
|
/sources/camera.cpp
|
UTF-8
| 4,425 | 2.9375 | 3 |
[] |
no_license
|
#include <math.h>
#include <iostream>
#include "camera.h"
namespace Project {
Camera::Camera(Eigen::Vector4d position, double rotX, double rotY, double rotZ) : position(position), shortBasis(4, 2) {
Eigen::Vector4d v1 = Eigen::Vector4d::UnitX();
Eigen::Vector4d v2 = Eigen::Vector4d::UnitY();
Eigen::Matrix3d m;
m = Eigen::AngleAxisd(rotX / 180.0 * M_PI, Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(rotY / 180.0 * M_PI, Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rotZ / 180.0 * M_PI, Eigen::Vector3d::UnitZ());
v1.head(3) = m * v1.head(3);
v2.head(3) = m * v2.head(3);
shortBasis.col(0) = v1;
shortBasis.col(1) = v2;
normalizeCameraBasis();
createFullBasis();
updateCubeTransform(-1, 1, -1, 1);
};
void Camera::moveFromBasis(double coef, int pos) {
position += fullBasis.col(pos) * coef;
}
void Camera::move(Eigen::Vector4d shift) {
position += shift;
}
void Camera::rotateBasis(double rotateXAngle, double rotateYAngle) {
Eigen::MatrixXd m = (Eigen::Matrix3d) (Eigen::AngleAxisd(rotateXAngle, fullBasis.col(1).head(3)) * Eigen::AngleAxisd(rotateYAngle, fullBasis.col(0).head(3)));
m.conservativeResize(4, 4);
m.col(3) = Eigen::Vector4d(0, 0, 0, 1);
m.row(3) = Eigen::Vector4d(0, 0, 0, 1);
fullBasis = m * fullBasis;
inversedFullBasis = inversedFullBasis * m.transpose();
}
void Camera::normalizeCameraBasis() {
shortBasis.col(0).normalize();
shortBasis.col(1).normalize();
}
void Camera::createFullBasis() {
Eigen::Vector3d vector1 = shortBasis.col(0).head(3);
Eigen::Vector3d vector2 = shortBasis.col(1).head(3);
Eigen::VectorXd vector3 = vector1.cross(vector2);
vector3.conservativeResize(4);
fullBasis.col(0) = shortBasis.col(0);
fullBasis.col(1) = shortBasis.col(1);
fullBasis.col(2) = vector3;
fullBasis.col(2).normalize();
fullBasis.col(3) = Eigen::Vector4d(0, 0, 0, 1);
inversedFullBasis = fullBasis.inverse();
}
void Camera::updateFullBasis() {
Eigen::Vector3d vector1 = fullBasis.col(0).head(3);
Eigen::Vector3d vector2 = fullBasis.col(1).head(3);
fullBasis.col(2).head(3) = vector1.cross(vector2);
inversedFullBasis = fullBasis.inverse();
}
void Camera::printFullBasis() {
std::cout << fullBasis << '\n';
}
void Camera::applyTransformToCamera(Eigen::Matrix4d transform) {
shortBasis = transform * shortBasis;
normalizeCameraBasis();
createFullBasis();
}
Eigen::Vector4d Camera::transformPointToCameraBasis(Eigen::Vector4d point) {
point -= position;
return inversedFullBasis * point;
}
Eigen::Vector4d Camera::transformToNearPlane(Eigen::Vector4d point) {
point = transformPointToCameraBasis(point);
if (point[2] == 0) {
return position;
}
return Eigen::Vector4d(-nearPlaneDistance * point[0] / point[2], -nearPlaneDistance * point[1] / point[2], -nearPlaneDistance, 1);
}
void Camera::updateCubeTransform(double l, double r, double b, double t) {
cubeTransform(0, 0) = 2 * nearPlaneDistance / (r - l);
cubeTransform(0, 2) = (r + l) / (r - l);
cubeTransform(1, 1) = (2 * nearPlaneDistance) / (t - b);
cubeTransform(1, 2) = (t + b) / (t - b);
cubeTransform(2, 2) = -(farPlaneDistance + nearPlaneDistance) / (farPlaneDistance - nearPlaneDistance);
cubeTransform(2, 3) = -2.0 * nearPlaneDistance * farPlaneDistance / (farPlaneDistance - nearPlaneDistance);
cubeTransform(3, 2) = -1;
}
void Camera::printCubeTransform() {
std::cout << cubeTransform << '\n';
}
Eigen::Vector4d Camera::transformToCube(Eigen::Vector4d point) {
return cubeTransform * point;
}
Eigen::Vector2d Camera::projectToScreen(Eigen::Vector4d point) {
point = transformToCube(point);
if (point[2] >= -1 && point[2] <= 1) {
return point.head(2);
}
return Eigen::Vector2d(-2, -2);
}
double Camera::getZ(Eigen::Vector4d point) {
point = transformToCube(point);
if (point[2] >= -1 && point[2] <= 1) {
return point[2];
}
return 2;
}
Eigen::Vector3d Camera::getLightVector() {
return fullBasis.col(2).head(3);
}
Eigen::Vector4d Camera::fullProject(Eigen::Vector4d point) {
point = transformToCube(point);
if (point[3] != 0) {
return point;
}
return Eigen::Vector4d(0, 0, 1000000, 1);
}
double Camera::getXAngle() {
return fieldOfView;
}
double Camera::getYAngle() {
return fieldOfView / displayRatio;
}
}
| true |
2f9e13e7719690051789a2fbc37a130eaf08c4f8
|
C++
|
Snake266/labs_cpp
|
/6/six.cpp
|
UTF-8
| 10,195 | 3 | 3 |
[] |
no_license
|
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#define sep_len 40
//Копирует строку и возвращает указатель новую строку
char* alloc_and_copy(char* str) {
char* res = new char[strlen(str) + 1];
if(!res) throw std::exception();
strcpy(res, str);
res[strlen(res)] = '\0';
return res;
}
//структура поссылки
struct parcel_t {
//Можно было бы и std::string, но это, скорее всего, посчитают читом
char* s_last_name; // Фамилия отправителя
char* s_first_name; // Имя отправителя
char* s_adress; // Адрес отправителя
char* r_last_name; // Фамилия получателя
char* r_first_name; // Имя получателя
char* r_adress; // Адрес получателя
double weight; //Вес поссылки
//Конструктор
parcel_t(char* s_ln, char* s_fn, char* s_a, char* r_ln, char* r_fn, char* r_a, double w) {
s_last_name = alloc_and_copy(s_ln);
s_first_name = alloc_and_copy(s_fn);
s_adress = alloc_and_copy(s_a);
r_last_name = alloc_and_copy(r_ln);
r_first_name = alloc_and_copy(r_fn);
r_adress = alloc_and_copy(r_a);
weight = w;
}
~parcel_t() {
//Так как мы все строки копируем, double free не будет, значит все классно
delete[] s_last_name;
delete[] s_first_name;
delete[] s_adress;
delete[] r_last_name;
delete[] r_first_name;
delete[] r_adress;
}
};
struct container {
parcel_t** array;
size_t size;
size_t capasity;
};
void _copy_parcel(parcel_t** dest, parcel_t** src, size_t n) {
memcpy(dest, src, n);
}
void push_back(container* c, parcel_t* p) {
if(c->array == NULL) {
c->capasity = 20;
c->size = 0;
c->array = new parcel_t*[c->capasity];
}
if(c->size == c->capasity) {
c->capasity *= 2;
parcel_t** tmp = new parcel_t*[c->capasity];
_copy_parcel(tmp, c->array, c->size);
delete[] c->array;
c->array = tmp;
}
c->size++;
c->array[c->size-1] = p;
}
//Функция, которая добавляет в конец коллекции новую поссылку
void new_parcel(container*);
//Печатаем таблицу
void print_parcel(parcel_t p);
void print_table(container* p);
//ищем поссылку по фамилии и имени отправителя
void find_by_sender(container* p);
void find_by_weight(container* p);
container* init_container() {
container* c = new container;
c->array = NULL;
c->size = 0;
c->capasity = 0;
return c;
}
int main() {
setlocale(LC_ALL, "Russian");
//Будем использовать std::vector, чтобы не писать свой std::vector
//вектор аллоцирует данные в динамической памяти, поэтому все по требованиям
container* parcels = init_container();
char choice = '0';
do {
std::cout << "Что вы хотите сделать?" << std::endl;
std::cout << "1. Добавить новую поссылку?\n2. Распечатать все посслыки\n"
<< "3. Найти все поссылки по их отправителю\n4. Найти поссылки больше заданного веса\n"
<< "0. Выйти\n(1/2/3/4/0): ";
std::cin >> choice;
std::cout << std::endl;
switch (choice)
{
case '1':
new_parcel(parcels);
break;
case '2':
print_table(parcels);
break;
case '3':
find_by_sender(parcels);
break;
case '4':
find_by_weight(parcels);
break;
case '0':
break;
default:
std::cout << "wrong argument" << std::endl;
break;
}
std::cout << std::endl;
} while(choice != '0');
return 0;
}
//Пишет message и вводит в переменную dest
//ради простоты можно условитс что строки не длиннее 80 символов
char* promt(const char* message) {
char buf[80];
std::cout << message;
std::cin.getline(buf, 80);
char* dest = new char[strlen(buf) + 1];
strcpy(dest, buf);
dest[strlen(dest)] = '\0';
return dest;
}
void new_parcel(container* p) {
std::cout << std::endl;
for(int i = 0; i < sep_len; ++i) {
std::cout << '-';
}
std::cout << std::endl;
std::cout << "Добавление новой поссылки" << std::endl;
//Аллоцируем память под наши параметры
char *s_last_name, *s_first_name, *s_adress,
*r_last_name, *r_first_name, *r_adress;
double weight;
std::cin.ignore(INT8_MAX, '\n');
//Вводим данные
s_last_name = promt("Введите фамилию отправителя: ");
s_first_name = promt("Введите имя отправителя: ");
s_adress = promt("Введите адрес отправителя: ");
r_last_name = promt("Введите фамилию получателя: ");
r_first_name = promt("Введите имя получателя: ");
r_adress = promt("Введите адрес получателя: ");
std::cout << "Введите вес посылки: ";
std::cin >> weight;
//Добавляем в конец массива объект
push_back(p, new parcel_t(s_last_name, s_first_name, s_adress,
r_last_name, r_first_name, r_adress, weight));
//Чистим память
delete[] s_last_name;
delete[] s_first_name;
delete[] s_adress;
delete[] r_last_name;
delete[] r_first_name;
delete[] r_adress;
for(int i = 0; i < sep_len; ++i) {
std::cout << '-';
}
std::cout << std::endl;
}
void print_parcel(parcel_t* p) {
for(int i = 0; i < sep_len; ++i) std::cout << '-';
std::cout << std::endl;
std::cout << "Фамилия отправителя: " << p->s_last_name << std::endl;
std::cout << "Имя отправителя : " << p->s_first_name << std::endl;
std::cout << "Адрес отправителя : " << p->s_adress << std::endl;
std::cout << "Фамилия получутеля : " << p->r_last_name << std::endl;
std::cout << "Имя получателя : " << p->r_first_name << std::endl;
std::cout << "Адрес получателя : " << p->r_adress << std::endl;
std::cout << "Вес поссылки : " << p->weight << std::endl;
for(int i = 0; i < sep_len; ++i) std::cout << '-';
std::cout << std::endl;
}
void print_table(container* p) {
if(p->size == 0) std::cout << "Поссылок нет" << std::endl;
else {
for(int i = 0; i < sep_len; ++i) {
std::cout << '-';
}
std::cout << std::endl;
for(int i = 0; i < p->size; ++i) {
print_parcel(p->array[i]);
}
}
}
void find_by_sender(container* p) {
for(int i = 0; i < sep_len; ++i) std::cout << '-';
std::cout << std::endl;
char sender_fname[80], sender_lname[80];
std::cin.ignore(INT8_MAX, '\n');
std::cout << "Введите фамилию отправителя: ";
std::cin.getline(sender_lname, 80);
std::cout << "Введите имя отправителя: ";
std::cin.getline(sender_fname, 80);
//Проходим по всему массиву
for(int i = 0; i < p->size; ++i) {
if(!strncmp(p->array[i]->s_first_name, sender_fname, strlen(p->array[i]->s_first_name))
&& !strncmp(p->array[i]->s_last_name, sender_lname, strlen(p->array[i]->s_last_name))) {
print_parcel(p->array[i]);
}
}
for(int i = 0; i < sep_len; ++i) std::cout << '-';
std::cout << std::endl;
}
//Напишем сортировку вставками. Мы не знаем, данные могут быть почти отсортированными, могут таковыми не быть
//но в задании нет ограничений, поэтому я хочу попробовать написать именно эту сортировку
void insertion_sort(parcel_t** p, size_t size) {
parcel_t *tmp, *key;
int i, j;
for(i = 0; i < size; ++i) {
key = p[i];
for(j = i - 1; j >= 0 && strcmp(p[j]->s_last_name, key->s_last_name) > 0; --j) {
p[j+1] = p[j];
}
p[j+1] = key;
}
}
void find_by_weight(container* p) {
for(int i = 0; i < sep_len; ++i) std::cout << '-';
std::cout << std::endl;
double w;
std::cout << "Введите вес поссылки: ";
std::cin >> w;
container* tmp = init_container();
for(int i = 0; i < p->size; ++i) {
if(p->array[i]->weight > w) push_back(tmp, p->array[i]);
}
/* std::sort(tmp.begin(), tmp.end(), [](parcel_t* a1, parcel_t* a2) {
//Создадим временные строки, которые мы будем дальше сравнивать
char* tmp1 = new char[strlen(a1->s_last_name) + strlen(a1->s_first_name) + 2];
char* tmp2 = new char[strlen(a2->s_last_name) + strlen(a2->s_first_name) + 2];
strcpy(tmp1, a1->s_last_name);
strcat(tmp1, a1->s_first_name);
strcpy(tmp2, a2->s_last_name);
strcat(tmp2, a2->s_first_name);
if(strcmp(tmp1, tmp2) < 0) {
delete[] tmp1;
delete[] tmp2;
return true;
}
else{
delete[] tmp1;
delete[] tmp2;
return false;
}
});*/
//сортировка
insertion_sort(tmp->array, tmp->size);
print_table(tmp);
}
| true |
5881451e0b8a9cba158c57c6eb8538fa15d07735
|
C++
|
zhangchenghgd/zeroballistics
|
/code/libs/toolbox/src/Utils.h
|
UTF-8
| 6,506 | 3.125 | 3 |
[] |
no_license
|
#ifndef LIB_UTILS_INCLUDED
#define LIB_UTILS_INCLUDED
#include <string>
#include <iostream>
#include <cmath>
#include <sstream>
#include "Datatypes.h"
#include "Exception.h"
#include "utility_Math.h"
#define UNUSED_VARIABLE(v) (void)v;
#define DELNULL(p) if(p) { delete p; p=NULL; }
#define DELNULLARRAY(p) if(p) { delete [] p; p=NULL; }
std::string addCr(const std::string & input);
std::string readTextFile(const std::string &filename);
void trim(std::string & str);
unsigned charCount(const std::string & str, char ch);
bool existsFile(const char * filename);
void generateSnD(float *data, unsigned size, float roughness, float maxHeight);
void enableFloatingPointExceptions(bool v = true);
//------------------------------------------------------------------------------
/**
* Smoothes a square array by averaging with the 8 surrounding elements.
*
* \param data The data to smooth. must be width*height elements.
* \param width The width of the array.
* \param height The height of the array.
* \param iterations The number of times to apply the smoothing filter.
*/
template <class T>
void averageArray(T *data, unsigned width, unsigned height, unsigned iterations)
{
double value;
T * new_data = new T[width*height];
T * tmp_pointer;
for (unsigned it=0; it<iterations; ++it)
{
for (unsigned row=0; row<height; ++row)
{
for (unsigned col=0; col<width; ++col)
{
value = data[col + width*row];
int c = 1;
if (col != 0)
{
c++;
value += data[col-1 + width* row ];
}
if (col != width-1)
{
c++;
value += data[col+1 + width* row ];
}
if (row != 0)
{
c++;
value += data[col + width*(row-1)];
}
if (row != height-1)
{
c++;
value += data[col + width*(row+1)];
}
value /= c;
new_data[col + width*row] = (T)value;
}
}
tmp_pointer = new_data;
new_data = data;
data = tmp_pointer;
}
if (iterations & 1)
{
memcpy(new_data, data, sizeof(T)*width*height);
delete [] data;
} else
{
delete [] new_data;
}
}
//------------------------------------------------------------------------------
/**
* Flips a data array vertically.
* This is done by exchanging lines (topmost with bottommost, then
* converging to the center).
*
* \param width The width of the data array.
* \param height The height of the data array.
* \param data The data to be flipped.
*/
template <class T>
void flipArrayVert(unsigned width, unsigned height, T * data)
{
T * tmp_line = new T[width];
for (unsigned row=0; row < height/2; ++row)
{
memcpy(tmp_line, &data[row*width], sizeof(T)*width);
memcpy(&data[row*width], &data[(height-1-row)*width], sizeof(T)*width);
memcpy(&data[(height-1-row)*width], tmp_line, sizeof(T)*width);
}
delete [] tmp_line;
}
//------------------------------------------------------------------------------
/**
* A template class representing a Node from a Quadtree.
*/
template<class T> class QuadNode
{
public:
//------------------------------------------------------------------------------
/**
* Build a quadtree with the specified depth.
* depth is number of levels-1.
*/
QuadNode(unsigned depth, T * parent = NULL) : parent_(parent)
{
if (depth)
{
upper_left_ = new T(depth-1, (T*)this);
upper_right_ = new T(depth-1, (T*)this);
lower_left_ = new T(depth-1, (T*)this);
lower_right_ = new T(depth-1, (T*)this);
} else
{
upper_left_ = NULL;
upper_right_ = NULL;
lower_left_ = NULL;
lower_right_ = NULL;
}
}
//------------------------------------------------------------------------------
virtual ~QuadNode()
{
DELNULL(upper_left_);
DELNULL(upper_right_);
DELNULL(lower_left_);
DELNULL(lower_right_);
}
//------------------------------------------------------------------------------
bool isLeaf() const
{
return upper_left_ == NULL;
}
//------------------------------------------------------------------------------
/**
* Expensive recursive function to determine the tree's depth.
*/
unsigned getDepth() const
{
if (upper_left_) return upper_left_->getDepth() +1;
else return 0;
}
T * parent_;
T * upper_left_;
T * upper_right_;
T * lower_left_;
T * lower_right_;
protected:
QuadNode() {}
};
//------------------------------------------------------------------------------
/**
* toString conversion with any argument type
*/
template <typename T>
inline std::string toString(T t)
{
std::ostringstream s;
s << t;
return s.str();
}
//------------------------------------------------------------------------------
/**
* toString specialization for uint8_t
*/
template < >
inline std::string toString(uint8_t t)
{
std::ostringstream s;
s << (unsigned)t;
return s.str();
}
//------------------------------------------------------------------------------
/**
* fromString conversion with any argument type
* i.e. int x = fromString<int>(text_string);
*/
template<typename RT, typename T, typename Trait, typename Alloc>
inline RT fromString( const std::basic_string<T, Trait, Alloc>& the_string )
{
std::basic_istringstream< T, Trait, Alloc> temp_ss(the_string);
RT num;
temp_ss >> num;
return num;
}
template< >
inline std::string fromString<std::string>( const std::string & the_string )
{
std::istringstream temp_ss(the_string);
std::string sub_str;
std::string value;
while (temp_ss >> sub_str)
{
if (!value.empty()) value += ' ';
value += sub_str;
}
return value;
}
#endif // ifndef LIB_UTILS_INCLUDED
| true |
cf5c655d5c625c5d7a3404754bc2c5e9402648f3
|
C++
|
kiriyasaa/learn-cpp
|
/Chapter P/617-introduction-to-iterators/back-to-range-based-for-loops.cpp
|
UTF-8
| 233 | 3.578125 | 4 |
[] |
no_license
|
#include <array>
#include <iostream>
int main()
{
std::array array{1, 2, 3};
// This does exactly the same as the loop we used before.
for (int i : array)
{
std::cout << i << ' ';
}
std::cout << '\n';
return 0;
}
| true |
5423611171e0f0a55b72bbf21b0be0ba699e8fc9
|
C++
|
Viswonathan06/AlgoDS
|
/Arrays/FourSumNumbers.cpp
|
UTF-8
| 2,235 | 3.171875 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
bool included(vector<vector<int>> arr, vector<int> m ){
for( vector<int> a: arr){
if( a == m){
return true;
}
}
return false;
}
vector<vector<int> > fourSum(vector<int> &arr, int k) {
// Store sums of all pairs
// in a hash table
// sort(arr.begin(), arr.end());
int n = arr.size();
int X = k;
vector<vector<int> > ans;
unordered_map<int, pair<int, int> > mp;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
mp[arr[i] + arr[j]] = { i, j };
// Traverse through all pairs and search
// for X - (current pair sum).
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int sum = arr[i] + arr[j];
// If X - sum is present in hash table,
if (mp.find(X - sum) != mp.end()) {
// Making sure that all elements are
// distinct array elements and an element
// is not considered more than once.
pair<int, int> p = mp[X - sum];
if (p.first != i && p.first != j
&& p.second != i && p.second != j) {
// cout << arr[i] << ", " << arr[j] << ", "
// << arr[p.first] << ", "
// << arr[p.second];
vector<int> a = {arr[i],arr[j], arr[p.first],arr[p.second]};
sort(a.begin(), a.end());
if(!included(ans,a))
ans.push_back(a);
// i++; j++;
// return;
}
}
}
}
return ans;
}
int main(){
vector<int> arr= { 10, 20, 30, 40, 1, 2 };
int X = 91;
// Function call
vector<vector<int>> ans = fourSum(arr, X);
for( vector<int> a: ans){
for( int x : a){
cout<<x<<" ";
}
cout<<"\n";
}
}
| true |
bbca7fb517dd65dcb9683ae671eed9bd34beac7b
|
C++
|
VityaP/AlgoLib
|
/simple_vector/simple_vector.cpp
|
UTF-8
| 2,715 | 3.375 | 3 |
[] |
no_license
|
#include "simple_vector.h"
template<typename T>
SimpleVector<T>::SimpleVector(){
data = nullptr;
size = 0;
capacity = 0;
}
template<typename T>
SimpleVector<T>::SimpleVector(size_t size)
: data(new T[size]),
size(size),
capacity(size)
{
}
template<typename T>
SimpleVector<T>::SimpleVector(const SimpleVector<T> &other)
: data(new T[other.capacity]),
size(other.size),
capacity(other.capacity)
{
copy(other.begin(), other.end(), begin());
}
// Move constructor
template<typename T>
SimpleVector<T>::SimpleVector(SimpleVector<T>&& other)
: data(other.data),
size(other.size),
capacity(other.capacity)
{
other.data = nullptr;
other.size = 0;
other.capacity = 0;
}
template<typename T>
void SimpleVector<T>::operator=(const SimpleVector<T> &other){
if( capacity < other.size ){
delete [] data;
data = new T[other.capacity];
capacity = other.capacity;
}
size = other.size;
copy(other.begin(), other.end(), begin());
}
// Move operator
template<typename T>
void SimpleVector<T>::operator=(SimpleVector<T> &&other){
delete [] data;
data = other.data;
size = other.size;
capacity = other.capacity;
other.data = nullptr;
other.size = 0;
other.capacity = 0;
}
template<typename T>
const T& SimpleVector<T>::operator[](size_t idx) const{
return data[idx];
}
template<typename T>
T& SimpleVector<T>::operator[](size_t idx){
return data[idx];
}
template<typename T>
const T* SimpleVector<T>::begin() const{
return data;
}
template<typename T>
T* SimpleVector<T>::begin(){
return data;
}
template<typename T>
const T* SimpleVector<T>::end() const{
return data + size;
}
template<typename T>
T* SimpleVector<T>::end(){
return data + size;
}
template<typename T>
size_t SimpleVector<T>::Size() const{
return size;
}
template<typename T>
size_t SimpleVector<T>::Capacity() const{
return capacity;
}
template<typename T>
void SimpleVector<T>::PushBack(const T &value){
if( size >= capacity ){
auto new_cap = 0;
if( capacity == 0 ){
new_cap = 1;
}
else{
new_cap = 2 * capacity;
}
capacity = new_cap;
auto new_data = new T[new_cap];
copy(begin(), end(), new_data);
delete [] data;
data = new_data;
}
data[size++] = value;
}
template<typename T>
SimpleVector<T>::~SimpleVector(){
if (data != nullptr){
delete [] data;
}
}
int main(){
return 0;
}
| true |
28858679b486a86f65212ca6860a3b9858a52d72
|
C++
|
realme72/beginning
|
/chapter 8/example/p812.cpp
|
UTF-8
| 795 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
#include <bits/stdc++.h>
using namespace std;
#define row1 3
#define col1 4
#define row2 col1
#define col2 2
int main()
{
int mat1[row1][col1],mat2[row2][col2],mat[row1][col2];
int i,j,k;
printf("Enter matrix mat1(%d*%d) row-wise \n",row1,col1);
for(i=0; i<row1; ++i)
for(j=0; j<col1; ++j)
scanf("%d",&mat1[i][j]);
printf("Enter matrix mat2(%d*%d) row-wise\n",row2,col2);
for(i=0; i<col1; ++i)
for(j=0; j<col2; ++j)
scanf("%d",&mat2[i][j]);
for(i=0; i<row1; ++i)
for(j=0; j<col2; ++j)
{
mat[i][j] = 0;
for(k=0; k<col1; ++k)
mat[i][j] += mat1[i][k] + mat2[k][j];
}
printf("Enter the resultant matrix mat\n");
for(i=0; i<row1; ++i)
{
for(j=0; j<col1; ++j)
printf("%d ",mat[i][j]);
printf("\n");
}
return 0;
}
| true |
51e6dda4f130d6d9f3de10ef36f211c08033cca8
|
C++
|
csamon/SurpriseControle
|
/SurpriseControle.ino
|
UTF-8
| 3,541 | 2.875 | 3 |
[] |
no_license
|
//
// ---------------------------
// Programme Surprise Controle
// ---------------------------
//
// Brancher aléatoirement des periph d'acquisition sur les entrées analogiques (un potar sur A1, A5 et un switch sur A4 par exemple),
// brancher un periph audio sur la pin 9 (buzzer, HP+transistor,..),
// brancher des periph de sortie aléatoirement sur les PIN de sorties (des LEDs sur 3,4,5 et un (moteur+diode roue libre) sur 10 par exemple).
// Alimenter la Arduino
//
//*****************************************************************************************************************************************************************
int out[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13}; //Utilisé pour declaration as Output dans setup()
int pitch = 1; // fréquence "auto gérée"
int pitchInd = 0; // Inducateur si boucle pitch++ ou pitch--
int thisPitch =0; // Frequence envoyée au buzzer
int a,b,c,d,e,f,g,h;
void setup() {
Serial.begin(9600);
for (int i=0; i < 14; i++){
pinMode(out[i] , OUTPUT);
}
digitalWrite(A0, HIGH); // Resistance pull up
digitalWrite(A1, HIGH); // pour utlisation d'un
digitalWrite(A2, HIGH); // BP
digitalWrite(A3, HIGH); //
digitalWrite(A4, HIGH); //
digitalWrite(A5, HIGH); //
}
void loop() {
acq(); //Fonction d'acquisition des entrées
analog_write(); // Fonction write sur sorties analog (PWM)
digital_to_analog_write(); // Fonction write sur sortie digital, emulation PWM
audio_out();// Fonction relative au pitch et buzzer
delay(50);
//debug_serial(); // /!\ Enlever les commentaires dans la fonction aussi !
}
int acq(void){
a = ((map(analogRead(A0), 10, 1023, 5, 10000))+(map(analogRead(A3), 10, 1023, 0, 255)));
b = map(analogRead(A0), 10, 1023, 0, 255);
c = map(analogRead(A1), 10, 1023, 0, 255);
d = map(analogRead(A2), 10, 1023, 0, 255);
e = map(analogRead(A3), 10, 1023, 0, 255);
f = map(analogRead(A4), 10, 1023, 0, 255);
g = map(analogRead(A5), 10, 1023, 0, 255);
}
int analog_write(void){ // Chaque potards controles un peu chaque sorties equitablements
analogWrite(3, ((b/6)+(c/6)+(d/6)+(e/6)+(f/6)+(g/6)));
analogWrite(5, ((b/6)+(c/6)+(d/6)+(e/6)+(f/6)+(g/6)));
analogWrite(6, ((b/6)+(c/6)+(d/6)+(e/6)+(f/6)+(g/6)));
analogWrite(10, ((b/6)+(c/6)+(d/6)+(e/6)+(f/6)+(g/6)));
analogWrite(11, ((b/6)+(c/6)+(d/6)+(e/6)+(f/6)+(g/6)));
}
int digital_to_analog_write(void){
PORTD = B10010100;
PORTB = B00110001;
delayMicroseconds(a);
PORTD = 0;
PORTB = 0;
delayMicroseconds(10000 - a);
}
int audio_out(void){
if(pitchInd == 0){
pitch = pitch + 20;
if(pitch >= 1000){
pitchInd = 1;
}
}
else if(pitchInd == 1){
pitch = pitch - 20;
if(pitch <= 15){
pitchInd = 0;
}
}
thisPitch = (map(analogRead(A0), 0, 1024, 30, 4000))+(map(analogRead(A1), 0, 1024, 30, 4000)+(map(analogRead(A2), 0, 1024, 30, 4000))
+ (map(analogRead(A3), 0, 1024, 30, 4000))+ (map(analogRead(A4), 0, 1024, 30, 4000))+
(map(analogRead(A5), 0, 1024, 30, 4000))+pitch);
tone(9, thisPitch, 10);
}
/*int debug_serial(void){
Serial.print("A0 = "); Serial.print(analogRead(A0));
Serial.print(" // A1 = "); Serial.print(analogRead(A1));
Serial.print(" // A2 = "); Serial.print(analogRead(A2));
Serial.print(" // A3 = "); Serial.print(analogRead(A3));
Serial.print(" // A4 = "); Serial.print(analogRead(A4));
Serial.print(" // A5 = "); Serial.println(analogRead(A5));
Serial.print("a = "); Serial.print(a);
Serial.print(" thisPitch = "); Serial.println(thisPitch);
}*/
| true |
696b768c368eba5249644815dc64d6a035a31e20
|
C++
|
houtaru/ACM-Notebook
|
/code/convexhull.h
|
UTF-8
| 968 | 3 | 3 |
[] |
no_license
|
// Complexity: O(nlog(n))
template <class T>
struct ConvexHull {
int head, tail;
T A[maxn], B[maxn];
ConvexHull(): head(0), tail(0) {}
bool bad(int l1, int l2, int l3) {
return 1.0 * (B[l3] - B[l1]) / (A[l1] - A[l3]) < 1.0 * (B[l2] - B[l1]) / (A[l1] - A[l2]);
}
void add(T a, T b) {
A[tail] = a; B[tail++] = b;
while (tail > 2 && bad(tail - 3, tail - 2, tail - 1)) {
A[tail - 2] = A[tail - 1];
B[tail - 2] = B[tail - 1];
tail--;
}
}
T get(T x) {
int l = 0, r = tail - 1;
while (l < r) {
int m = (l + r) / 2;
long long f1 = A[m] * x + B[m];
long long f2 = A[m + 1] * x + B[m + 1];
if (f1 <= f2) l = m + 1;
else r = m;
}
return A[l] * x + B[l];
}
};
| true |
abec92494fe0cf9d12c5e65bb0bfe4af0865de02
|
C++
|
gitjinyubao/MyProject
|
/PreviousProjects/C++Project/友元类/友元成员函数/Person.h
|
GB18030
| 327 | 2.6875 | 3 |
[] |
no_license
|
#ifndef PERSON_H
#define PERSON_H
#include<string>
using namespace std;//ûͲstring
class Member;
class Person
{
friend class Member;
public:
Person(string name,string sex,int age);
private:
void printMessage();
string m_strName;
string m_strSex;
int m_iAge;
};
#endif
| true |
56b9b151abf1b099a10e84d165af9e489bf65521
|
C++
|
kishankr7979/CP
|
/largest_prime_factor.cpp
|
UTF-8
| 1,161 | 2.640625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define MAX 10000
class Solution {
public:
long long int largestPrimeFactor(int N) {
// code here
bool prime[N + 1];
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (int i = 2; i <= N; i++)
{
if (prime[i])
{
for (int j = i * i; j <= N; j += i)
{
prime[j] = false;
}
}
}
long long int ans = INT_MIN;
for (long long int i = 2; i <= N; i++)
{
if (prime[i] && N % i == 0)
{
ans = max(ans, i);
N /= i;
}
}
return ans;
}
};
int main()
{
ios_base :: sync_with_stdio(false);
/*cin.tie(NULL);
cout.tie(NULL);*/
int T;
cin >> T;
while (T--)
{
//cout << 1 << endl;
vector<bool> prime(10001, true);
prime[0] = prime[1] = false;
for (int i = 2; i <= 10000; i++)
{
if (prime[i])
{
for (int j = i * i; j <= 10000; j += i)
{
prime[j] = false;
}
}
}
int n;
cin >> n;
long long int ans = INT_MIN;
for (long long int i = 2; i * i <= MAX; i++)
{
if (prime[i] && n % i == 0)
{
ans = max(ans, i);
}
}
cout << ans << endl;
}
return 0;
}
| true |
49b842e5d5d591ed30986e31187b659f08a47031
|
C++
|
cevazrem/Calculator
|
/Calc.cpp
|
UTF-8
| 2,380 | 3.453125 | 3 |
[] |
no_license
|
#include <iostream>
#include <stack>
class LexAnalyser {
private:
int cur;
public:
int get_lex();
};
int LexAnalyser::get_lex() {
while ((cur = getchar()) && (isspace(cur)) && (cur != ';')) {}
return cur;
}
class Parser {
private:
LexAnalyser scanner;
int cur;
std::stack <int> result;
void get_lex();
void L();
void C();
void A();
void M();
void K();
// void num();
public:
int calculate();
};
void Parser::get_lex() {
cur = scanner.get_lex();
}
//L -> C {+ C}
void Parser::L() {
C();
while (cur == '+') {
get_lex();
C();
int second_val = result.top();
result.pop();
int first_val = result.top();
result.pop();
result.push(first_val + second_val);
}
}
//C -> A {- A}
void Parser::C() {
A();
while (cur == '-') {
get_lex();
C();
int second_val = result.top();
result.pop();
int first_val = result.top();
result.pop();
result.push(first_val - second_val);
}
}
//A -> M {* M}
void Parser::A() {
M();
while (cur == '*') {
get_lex();
C();
int second_val = result.top();
result.pop();
int first_val = result.top();
result.pop();
result.push(first_val * second_val);
}
}
//M -> K {/ K}
void Parser::M() {
K();
while (cur == '/') {
get_lex();
C();
int second_val = result.top();
result.pop();
int first_val = result.top();
result.pop();
result.push(first_val / second_val);
}
}
//K -> num | (L)
void Parser::K() {
if (isdigit(cur)) {
int val = 0, i = 1;
while (isdigit(cur)) {
val = val * 10 + (cur - '0');
// std::cout << "val:" << val;
i++;
get_lex();
}
// std::cout << val << std::endl;
result.push(val);
// get_lex();
} else if (cur == '(') {
get_lex();
L();
if (cur != ')') throw "Syntax error: wrong usage of ()";
get_lex();
} else {
throw "Syntax error: undefined symbol";
}
}
int Parser::calculate() {
get_lex();
L();
// std::cout << cur;
if (cur != ';') throw "Syntax error wrong end of string";
return result.top();
}
int main(void) {
try {
Parser my_pars;
std::cout << my_pars.calculate() << std::endl;
} catch (const char *err) {
std::cerr << err << std::endl;
}
}
| true |
f3968c3a466c2852501d1fec0e7687e916b808ca
|
C++
|
tommyg141/EX4_b
|
/sources/Board.hpp
|
UTF-8
| 821 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
#include <map>
#include "City.hpp"
#include "Color.hpp"
#include <set>
using namespace std;
namespace pandemic
{
class Board
{
set<City> research_station;
set<Color> discovered_cure;
static std::map<City, std::set<City>> connect_maps;
std::map<City, int> temp;
static std::map< City, Color> city_color;
public:
Board() {};
bool is_clean();
int &operator[](City s);
friend std::ostream &operator<<(std::ostream &output, const Board &boaed);
void remove_cures();
void remove_station();
static bool is_connected(City a, City b);
bool check_research_station(City n1);
static Color get_color(City c);
void update_cure(Color c);
void update_station(City c);
void update_level(City c , int n );
bool have_cure(Color c);
};
}
| true |
2b7edf1bf2cf35fac78282eeb0ce6ddc72bfb30a
|
C++
|
Wprofessor/DataStruct
|
/队列.cpp
|
GB18030
| 1,078 | 3.375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<iostream>
#include<string.h>
#define MAXSIZE 100
using namespace std;
typedef int datatype;
typedef struct {
datatype a[MAXSIZE];
int front;
int real;
} sequence_queue;
void init( sequence_queue *q ) {
q->front = q->real = 0;
}
int empty(sequence_queue q) {
return ( q.front == q.real )?1:0;
}
void display( sequence_queue q ) {
if( empty(q) ) {
cout<<"Ϊ"<<endl;
} else {
for( int i = q.front; i < q.real ; i++ ) {
cout<<q.a[i]<<" ";
}
}
}
datatype get( sequence_queue q ) {
if( empty(q) ) {
cout<<"Ϊ"<<endl;
exit(1);
} else {
return q.a[q.front];
}
}
void insert( sequence_queue *q, datatype x) {
if( q->real == MAXSIZE ) {
cout<<""<<endl;
} else {
q->a[q->real] = x;
q->real++;
}
}
void del(sequence_queue *q) {
if( q->front == q->real ) {
cout<<"Ϊ"<<endl;
} else {
q->front++;
}
}
int main() {
sequence_queue q;
init(&q);
insert(&q,0);
insert(&q,1);
insert(&q,2);
insert(&q,3);
insert(&q,4);
display(q);
del(&q);
cout<<endl;
display(q);
return 0;
}
| true |
5de9b08d252f0a1814af1a7968b1bf2684549a7d
|
C++
|
roomyroomy/algorithm
|
/algospot/ROOTS.cpp
|
UTF-8
| 835 | 3.34375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
double calc(vector<double> &equation, double x)
{
double result = 0.0;
int n = equation.size();
for(int idx = 0; idx < n; idx++)
{
result += pow(x, (n - idx - 1));
}
return result;
}
double solve(vector<double> &equation)
{
double result = 0.0, low = -10.0, high = 10.0;
double aaa = calc(equation, low);
double bbb = calc(equation, high);
return result;
}
int main()
{
std::ios::sync_with_stdio(false);
int tc, n;
cin >> tc;
for(int idxCase = 0; idxCase < tc; idxCase++)
{
vector<double> equation;
cin >> n;
for(int idxVal = 0; idxVal < n + 1; idxVal++)
{
double d;
cin >> d;
equation.push_back(d);
}
cout << solve(equation) << endl;
}
return 0;
}
/*
2
3
1.00 -6.00 11.00 -6.00
2
1.00 -12.50 31.50
*/
| true |
dc7bbac7039297873d50b7540cfa311fc09673a7
|
C++
|
myartings/yfs-1
|
/lock_server.cc
|
UTF-8
| 1,762 | 2.78125 | 3 |
[] |
no_license
|
// the lock server implementation
#include "lock_server.h"
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "jsl_log.h"
lock_server::lock_server():
nacquire (0)
{
pthread_mutex_init(&mutex, NULL);
}
lock_protocol::status
lock_server::stat(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret = lock_protocol::OK;
printf("stat request from clt %d\n", clt);
r = nacquire;
return ret;
}
lock_protocol::status
lock_server::acquire(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret;
pthread_mutex_lock(&mutex);
std::map<lock_protocol::lockid_t, int>::iterator it = locks.find(lid);
if (it == locks.end()) {
locks[lid] = 1;
conditions[lid] = new pthread_cond_t;
pthread_cond_init(conditions[lid], NULL);
ret = lock_protocol::OK;
} else if (it->second == 0) {
locks[lid] = 1;
ret = lock_protocol::OK;
} else {
while (1) {
pthread_cond_wait(conditions[lid], &mutex);
if (it->second == 0)
break;
}
it->second = 1;
}
pthread_mutex_unlock(&mutex);
r = 0;
return ret;
}
lock_protocol::status
lock_server::release(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret = lock_protocol::OK;
jsl_log(JSL_DBG_2, "lock_server::release called with lockid %llu\n", lid);
pthread_mutex_lock(&mutex);
jsl_log(JSL_DBG_2, "lock_server::release (%llu) grant mutex\n", lid);
locks[lid] = 0;
pthread_cond_signal(conditions[lid]);
pthread_mutex_unlock(&mutex);
jsl_log(JSL_DBG_2, "lock_server::release (%llu) returns\n", lid);
r = 0;
return ret;
}
| true |
98f65b06f23a5b76c1aeca877dc3032988529631
|
C++
|
godnoTA/acm.bsu.by
|
/3. Структуры данных/28. Расписание #1089/[OK]224604.cpp
|
UTF-8
| 2,992 | 2.84375 | 3 |
[
"Unlicense"
] |
permissive
|
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <algorithm>
int main() {
std::ifstream fin("input.txt");
int m, n;
fin >> n;//quantity of jobs
std::vector<int> sequence(n, 0);//contains optimal sequence
std::vector<long long> processTimes(n, 0ll);//contains process time for each job
std::vector<long long> deadlines(n, 0ll);//contains deadline for each job
//getting process time and deadline for each job
for (int i = 0; i < n; ++i) {
fin >> processTimes[i];
fin >> deadlines[i];
}
fin >> m;//quantity of job orders
std::set<int> fromToMatrix[n];//contains job orders from -> to
std::vector<int> toFromMatrix[n];//contains job orders to -> from
int from, to;
for (int i = 0; i < m; ++i) {
fin >> from;
fin >> to;
fromToMatrix[--from].insert(--to);
toFromMatrix[to].push_back(from);
}
fin.close();
int place = 0;
std::set< std::pair<long long, int> > candidatesForSequence; //sorted by decreasing deadline, contains number of job and its deadline
//inserts candidates with zero jobs after and these candidates automatically sorted by decreasing deadlines
for (int i = 0; i < n; ++i)
if (fromToMatrix[i].empty())
candidatesForSequence.insert(std::make_pair(-deadlines[i], i));
while (place < n) {
//get the job which we'll be made (from last to the first)
sequence[place] = candidatesForSequence.begin()->second;
candidatesForSequence.erase(candidatesForSequence.begin());
//we have deleted job and now we have to delete it from fromToMatrix
//we run through toFromMatrix because it contains numbers of jobs which we have to delete the job from
for (auto it : toFromMatrix[sequence[place]]) {
fromToMatrix[it].erase(sequence[place]);
//if all jobs after it are processed, it becomes the candidate
if (fromToMatrix[it].empty()) {
candidatesForSequence.insert(std::make_pair(-deadlines[it], it));
}
}
++place; //iterates to the next member of sequence
}
long long c = 0ll, maximum = -1ll;
int maximumIndex = -1;
long long t;
//finds job with max fee and its index from the optimal sequence
for (int i = --place; i >= 0; --i) {
c += processTimes[sequence[i]];
t = std::max(c - deadlines[sequence[i]], 0ll);
if (t >= maximum) {
maximum = t;
maximumIndex = sequence[i];
}
}
std::ofstream fout("output.txt");
//outputs job's index and max fee
fout << ++maximumIndex << " " << maximum << std::endl;
//outputs optimal sequence
for (int i = place; i > 0; --i)
fout << sequence[i] + 1 << std::endl;
fout << sequence[0] + 1;
fout.close();
return 0;
}
| true |
765cdb21fd4fbf4076b367e7d7a738bf567a37d6
|
C++
|
jkred369/code_lib
|
/lock_tools.cpp
|
UTF-8
| 1,697 | 3.546875 | 4 |
[] |
no_license
|
//基于pthread_mutex 实现一个互斥锁
class Mutex
{
public:
Mutex()
{
m_count = 0;
m_threadID = 0;
//pthread_mutexattr_t attr;
//pthread_mutexattr_init(&attr);
//pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
//pthread_mutex_init(&m_mutex, &attr);
pthread_mutex_init(&m_mutex,0);
}
~Mutex()
{
pthread_mutex_destroy(&m_mutex);
}
void lock()
{
if(m_count && m_threadID == pthread_self())
{
++m_count;
return;
}
pthread_mutex_lock(&m_mutex);
++m_count;
m_threadID = pthread_self();
}
void unlock()
{
if(m_count > 1)
{
m_count--;
return;
}
--m_count;
m_threadID = 0;
pthread_mutex_unlock(&m_mutex);
}
private:
pthread_mutex_t m_mutex;
pthread_t m_threadID;
int m_count;
};
// 实现一个互斥锁对象,可以在退出作用域是被析构(unlock)
class Locker
{
public:
Locker(Mutex& mutex)
: _mutex(mutex)
{
_mutex.lock();
}
~Locker()
{
_mutex.unlock();
}
private:
Mutex& _mutex;
};
class ReverseLocker
{
public:
ReverseLocker( Mutex& mutex )
: _mutex( mutex )
{
_mutex.unlock();
}
~ReverseLocker()
{
_mutex.lock();
}
private:
Mutex& _mutex;
};
| true |
2c49733aa21841378f067f61e2664a24c827634e
|
C++
|
angrilove/Repositories
|
/ThinkInCpp/circle.h
|
UTF-8
| 305 | 2.71875 | 3 |
[] |
no_license
|
#ifndef CIRCLE_H
#define CIRCLE_H
#include "shape.h"
class Circle : public Shape
{
public:
Circle(Point2D p, double rdi = 0.5) : Shape(p)
{
radius = rdi;
}
void draw()
{
// do someting here
}
private:
double radius; // error: double radius = 0.5;
};
#endif
| true |
6bd23adc89ed5931a8bc84e906c04bf52a4e6a39
|
C++
|
jimmylin1017/UVA
|
/12019 - Doom's Day Algorithm.cpp
|
UTF-8
| 477 | 3.09375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
string day[7] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"};
int mon[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int n,m,d,count;
cin>>n;
while(n--)
{
cin>>m>>d;
count = 0;
for(int i=1;i<m;i++)
{
count+=mon[i];
}
count+=d;
count = (count+5)%7; // 2011/1/1 Saturday 2011/1/0 Friday
cout<<day[count]<<endl;
}
return 0;
}
| true |
ee08b3c18939b0c2dd064a47854dbc302465e5cb
|
C++
|
NullSeile/UITools
|
/src/Graph.cpp
|
UTF-8
| 7,738 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "Graph.h"
#include "Line.h"
#include <cmath>
#include "Global.h"
namespace ui {
Graph::Graph(const std::string& id)
: UIObject(id)
, m_pos(0, 0)
, m_size(100, 100)
, m_backColor(sf::Color::White)
, m_axisColor({ 10, 10, 10 })
, m_axisWidth(2)
, m_gridWidth(1)
{
}
void Graph::SetPosition(const ui::Vec2f& pos)
{
m_pos = pos;
}
void Graph::SetSize(const ui::Vec2f& size)
{
m_size = size;
}
void Graph::SetRange(const ui::Vec2f& xRange, const ui::Vec2f& yRange)
{
m_xRange = xRange;
m_yRange = yRange;
}
void Graph::SetXRange(const ui::Vec2f& range)
{
m_xRange = range;
}
void Graph::SetYRange(const ui::Vec2f& range)
{
m_yRange = range;
}
void Graph::SetBackgrowndColor(const sf::Color& color)
{
m_backColor = color;
}
void Graph::SetAxisColor(const sf::Color& color)
{
m_axisColor = color;
}
void Graph::SetAxisWidth(const float& width)
{
m_axisWidth = width;
}
ui::Vec2f Graph::MapPosToCoords(const ui::Vec2f& pos)
{
return ui::Vec2f
(
map(pos.x, m_xRange.min, m_xRange.max, 0, m_size.x),
map(pos.y, m_yRange.min, m_yRange.max, m_size.y, 0)
) + m_pos;
}
ui::Vec2f Graph::MapCoordsToPos(const ui::Vec2f& coords)
{
return
{
map(coords.x - m_pos.x, 0, m_size.x, m_xRange.min, m_xRange.max),
map(coords.y - m_pos.y, m_size.y, 0, m_yRange.min, m_yRange.max)
};
}
void Graph::ClearAll()
{
m_plots.clear();
m_arrows.clear();
}
void Graph::ClearArrows()
{
m_arrows.clear();
}
void Graph::ClearPlots()
{
m_plots.clear();
}
void Graph::Scatter(const std::vector<ui::Vec2f>& data, const ScatterDef& props)
{
m_scatters.push_back({ data, props });
}
void Graph::Plot(const std::vector<ui::Vec2f>& data, const PlotDef& props)
{
m_plots.push_back({ data, props });
}
void Graph::Arrow(const ui::Vec2f& pos, const ui::Vec2f& size, const ArrowDef& props)
{
m_arrows.push_back({ { pos, size }, props });
}
void Graph::Fit(const float& margin)
{
ui::Vec2f xRange = { INFINITY, -INFINITY };
ui::Vec2f yRange = { INFINITY, -INFINITY };
for (auto& [scatter, prop] : m_scatters)
{
for (const ui::Vec2f& p : scatter)
{
xRange.min = std::min(xRange.min, p.x);
xRange.max = std::max(xRange.max, p.x);
yRange.min = std::min(yRange.min, p.y);
yRange.max = std::max(yRange.max, p.y);
}
}
for (auto& [plot, prop] : m_plots)
{
for (const ui::Vec2f& p : plot)
{
xRange.min = std::min(xRange.min, p.x);
xRange.max = std::max(xRange.max, p.x);
yRange.min = std::min(yRange.min, p.y);
yRange.max = std::max(yRange.max, p.y);
}
}
for (auto& [arrow, prop] : m_arrows)
{
auto& [p, size] = arrow;
xRange.min = std::min(xRange.min, p.x);
xRange.max = std::max(xRange.max, p.x);
yRange.min = std::min(yRange.min, p.y);
yRange.max = std::max(yRange.max, p.y);
}
float xMargin = (xRange.max - xRange.min) * margin;
float yMargin = (yRange.max - yRange.min) * margin;
xRange.min -= xMargin;
xRange.max += xMargin;
yRange.min -= yMargin;
yRange.max += yMargin;
SetRange(xRange, yRange);
}
ui::Vec2f Graph::CalculateAxisStep()
{
ui::Vec2f n(1, 1);
ui::Vec2f e(1, 1);
float xDelta = n.x * powf(10.f, e.x);
float yDelta = n.y * powf(10.f, e.y);
while (true)
{
if (MapPosToCoords({ xDelta, 0 }).x - MapPosToCoords({ 0, 0 }).x < 100)
{
switch ((int)n.x)
{
case 1:
n.x = 2;
break;
case 2:
n.x = 5;
break;
case 5:
n.x = 1;
e.x += 1;
}
xDelta = n.x * powf(10, e.x);
}
else if (MapPosToCoords({ xDelta, 0 }).x - MapPosToCoords({ 0, 0 }).x > 500)
{
switch ((int)n.x)
{
case 1:
n.x = 5;
e.x -= 1;
break;
case 2:
n.x = 1;
break;
case 5:
n.x = 2;
}
xDelta = n.x * powf(10, e.x);
}
else
break;
}
while (true)
{
if (MapPosToCoords({ 0, yDelta }).y - MapPosToCoords({ 0, 0 }).y > -100)
{
switch ((int)n.y)
{
case 1:
n.y = 2;
break;
case 2:
n.y = 5;
break;
case 5:
n.y = 1;
e.y += 1;
}
yDelta = n.y * powf(10, e.y);
}
else if (MapPosToCoords({ 0, yDelta }).y - MapPosToCoords({ 0, 0 }).y < -500)
{
switch ((int)n.y)
{
case 1:
n.y = 5;
e.y -= 1;
break;
case 2:
n.y = 1;
break;
case 5:
n.y = 2;
}
yDelta = n.y * powf(10, e.y);
}
else
break;
}
return { xDelta, yDelta };
}
void Graph::Draw(sf::RenderWindow& window)
{
sf::RectangleShape back;
back.setSize(m_size);
back.setPosition(m_pos);
back.setFillColor(m_backColor);
window.draw(back);
// Calculate steps
ui::Vec2f delta = CalculateAxisStep();
// Draw grid
for (float x = snap(m_xRange.min, delta.x); x < m_xRange.max; x += delta.x)
{
ui::Vec2f p0 = MapPosToCoords({ x, m_yRange.min });
ui::Vec2f p1 = MapPosToCoords({ x, m_yRange.max });
ui::Line h("h", p0, p1);
h.SetColor({ 150, 150, 150 });
h.SetWidth(m_gridWidth);
h.Draw(window);
}
for (float y = snap(m_yRange.min, delta.y); y < m_yRange.max; y += delta.y)
{
ui::Vec2f p0 = MapPosToCoords({ m_xRange.min, y });
ui::Vec2f p1 = MapPosToCoords({ m_xRange.max, y });
ui::Line v("v", p0, p1);
v.SetColor({ 150, 150, 150 });
v.SetWidth(m_gridWidth);
v.Draw(window);
}
// X axis
ui::Vec2f axisX1 = MapPosToCoords({ m_xRange.min, 0 });
ui::Vec2f axisX2 = MapPosToCoords({ m_xRange.max, 0 });
ui::Line x("x", axisX1, axisX2);
x.SetColor(m_axisColor);
x.SetWidth(m_axisWidth);
x.Draw(window);
// Y axis
ui::Vec2f axisY1 = MapPosToCoords({ 0, m_yRange.min });
ui::Vec2f axisY2 = MapPosToCoords({ 0, m_yRange.max });
ui::Line y("y", axisY1, axisY2);
y.SetColor(m_axisColor);
y.SetWidth(m_axisWidth);
y.Draw(window);
// Draw scatters
for (auto& [scatter, prop] : m_scatters)
{
//ui::Vec2f prevPos = MapPosToCoords(scatter[0]);
for (int i = 0; i < scatter.size(); i++)
{
//ui::Vec2f newPos = MapPosToCoords(scatter[i]);
//ui::Vec2f delta = newPos - prevPos;
ui::Vec2f pos = scatter[i];
//if (delta.Length() > 100)
if (!(pos.x < m_xRange.min || pos.x > m_xRange.max || pos.y < m_yRange.min || pos.y > m_yRange.max))
{
sf::CircleShape shape;
shape.setRadius(prop.radius);
shape.setOrigin(prop.radius, prop.radius);
shape.setPosition(pos);
shape.setFillColor(prop.color);
window.draw(shape);
//prevPos = newPos;
}
}
}
// Draw plots
for (auto&[plot, prop] : m_plots)
{
ui::Vec2f prevPos = MapPosToCoords(plot[0]);
for (uint i = 1; i < plot.size(); i++)
{
ui::Vec2f newPos = MapPosToCoords(plot[i]);
ui::Vec2f delta = newPos - prevPos;
if (delta.Length() > 5.f || prop.optimize)
{
if (!((prevPos.x - m_pos.x < 0 || prevPos.x - m_pos.x > m_size.x || prevPos.y - m_pos.y < 0 || prevPos.y - m_pos.y > m_size.y) &&
(newPos.x - m_pos.x < 0 || newPos.x - m_pos.x > m_size.x || newPos.y - m_pos.y < 0 || newPos.y - m_pos.y > m_size.y)))
{
ui::Line l("l", prevPos, newPos);
l.SetWidth(prop.width);
l.SetColor(prop.color);
l.Draw(window);
}
prevPos = newPos;
}
}
if (prop.cyclic)
{
ui::Line l("l", prevPos, MapPosToCoords(plot[0]));
l.SetWidth(prop.width);
l.SetColor(prop.color);
l.Draw(window);
}
}
// Draw arrows
for (auto&[arrow, prop] : m_arrows)
{
auto& [pos, size] = arrow;
ui::Vec2f iPos = MapPosToCoords(pos);
ui::Vec2f fPos = MapPosToCoords(pos + size);
ui::Line l("l", iPos, fPos);
l.SetWidth(prop.width);
l.SetColor(prop.color);
l.Draw(window);
}
}
Graph::~Graph()
{
}
}
| true |
5fa5d0016e5e25a57f2d2d720c10f57df86e834d
|
C++
|
prudentboy/leetcode
|
/Solutions/229.majority-element-ii.cpp
|
UTF-8
| 983 | 3.140625 | 3 |
[] |
no_license
|
/*
* @lc app=leetcode id=229 lang=cpp
*
* [229] Majority Element II
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> ans;
if (nums.empty()) return ans;
int ma(0), mb(0), cnta(0), cntb(0);
for (int n : nums)
{
if (ma == n) ++cnta;
else if (mb == n) ++cntb;
else if (cnta == 0)
{
ma = n;
++cnta;
}
else if (cntb == 0)
{
mb = n;
++cntb;
}
else
{
--cnta;
--cntb;
}
}
cnta = 0;
cntb = 0;
for (int n : nums)
{
if (n == ma) ++cnta;
else if (n == mb) ++cntb;
}
if (cnta > nums.size() / 3) ans.push_back(ma);
if (cntb > nums.size() / 3) ans.push_back(mb);
return ans;
}
};
| true |
18c717ab56ca8904241eb98b2e63b00f41277055
|
C++
|
coreymack224/Ent
|
/Ent/FullTextureRenderer.h
|
UTF-8
| 627 | 2.609375 | 3 |
[] |
no_license
|
//FullTextureRenderer.h
#pragma once
#include"RendererBase.h"
class FullTextureRenderer : public RendererBase {
vector<GLfloat*> positions;
vector<VertexArrayObject*> vaos;
vector<GLfloat*> scales;
vector<GLuint*> textures;
GLfloat* transformMatrix;
int positionUL, scaleUL, textureUL, transformMatrixUL;
public:
inline void Push(GLfloat* position, VertexArrayObject* vao, GLfloat* scale, GLuint* texture) {
positions.push_back(position);
vaos.push_back(vao);
scales.push_back(scale);
textures.push_back(texture);
}
void Render();
FullTextureRenderer(GLfloat* transformMatrix);
~FullTextureRenderer();
};
| true |
b5d8a95c47b2cd5575a3949ca0d6d7c4bdce53be
|
C++
|
RoseAlice2018/AlgorithmProblemSet
|
/公司/字节跳动/技术中台/124.cpp
|
UTF-8
| 1,291 | 3.0625 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(NULL), right(NULL) {}
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int ret = INT_MIN;
int maxSum(TreeNode* root) {
//1. root
//2. root left
//3. root right
//4. left
//5. right
//6. root left right
if(root==NULL)
return 0;
int left_max = max(maxSum(root->left),0);
int right_max = max(maxSum(root->right),0);
int sum=0;
sum=root->val+left_max+right_max;
ret=max(ret,sum);
sum = max(left_max,right_max)+root->val;
return sum;
}
int maxPathSum(TreeNode* root)
{
maxSum(root);
return ret;
}
};
| true |
9f9931afdd1e3777e16f5b74488d0b739165edb9
|
C++
|
kunni918/magic
|
/cpp/src/core/simulations/VdpTag.cpp
|
UTF-8
| 8,582 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
#include "core/simulations/VdpTag.h"
#include "core/Util.h"
#include <opencv2/core/types.hpp>
#include <opencv2/imgproc.hpp>
#include <random>
namespace simulations {
VdpTag::Action VdpTag::Action::Rand() {
Action action(std::uniform_real_distribution<float>(0, 2 * PI)(Rng()));
action.look = std::bernoulli_distribution(0.5)(Rng());
return action;
}
list_t<list_t<VdpTag::Action>> VdpTag::Action::CreateHandcrafted(size_t length) {
list_t<list_t<Action>> macro_actions;
for (size_t i = 0; i < 8; i++) {
macro_actions.emplace_back();
for (size_t j = 0; j < length; j++) {
macro_actions.back().push_back({static_cast<float>(i) * 2 * PI / 8});
}
}
Action trigger_action;
trigger_action.look = true;
macro_actions.emplace_back();
macro_actions.back().emplace_back(trigger_action);
return macro_actions;
}
/* ====== Construction related functions ====== */
VdpTag::VdpTag() : _is_terminal(false) {
}
VdpTag VdpTag::CreateRandom() {
return SampleBeliefPrior();
}
/* ====== Belief related functions ====== */
VdpTag VdpTag::SampleBeliefPrior() {
VdpTag sim;
sim.ego_agent_position = vector_t(0.0f, 0.0f);
sim.exo_agent_position.x = std::uniform_real_distribution<float>(-4.0, 4.0)(Rng());
sim.exo_agent_position.y = std::uniform_real_distribution<float>(-4.0, 4.0)(Rng());
return sim;
}
float VdpTag::Error(const VdpTag& other) const {
float error = 0;
error += (ego_agent_position - other.ego_agent_position).norm();
error += (exo_agent_position - other.exo_agent_position).norm();
return error / 2;
}
/* ====== Bounds related functions ====== */
float VdpTag::BestReward() const {
if (_is_terminal) { return 0; } // Return value of 0 needed for DESPOT.
float distance = std::max(0.0f, (exo_agent_position - ego_agent_position).norm() - TAG_RADIUS);
float max_distance_per_step = AGENT_SPEED * DELTA + 4.0f * DELTA + 3 * POS_STD ;
size_t steps = static_cast<size_t>(round(ceilf(distance / max_distance_per_step)));
if (steps <= 1) {
return TAG_REWARD;
} else {
return (1 - powf(GAMMA, static_cast<float>(steps) - 1)) / (1 - static_cast<float>(steps)) * STEP_REWARD +
powf(GAMMA, static_cast<float>(steps) - 1) * TAG_REWARD;
}
}
/* ====== Stepping functions ====== */
float VdpTag::Cross(const vector_t& a, const vector_t& b) {
return a.x * b.y - b.x * a.y;
}
vector_t VdpTag::VdpDynamics(const vector_t& v) const {
return {
MU * (v.x - v.x * v.x * v.x / 3 - v.y),
v.x / MU
};
}
vector_t VdpTag::Rk4Step(const vector_t& v) const {
float h = RK4_STEP_SIZE;
vector_t k1 = VdpDynamics(v);
vector_t k2 = VdpDynamics(v + k1 * h / 2);
vector_t k3 = VdpDynamics(v + k2 * h / 2);
vector_t k4 = VdpDynamics(v + k3 * h);
return v + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4);
}
vector_t VdpTag::BarrierStop(const vector_t& v, const vector_t& d) const {
float shortest_u = 1.0f + 2 * std::numeric_limits<float>::epsilon();
vector_t q = v;
vector_t s = d;
for (vector_t dir : list_t<vector_t>{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) {
vector_t p = 0.2f * dir;
vector_t r = 2.8f * dir;
float rxs = Cross(r, s);
if (rxs == 0.0f) {
continue;
} else {
vector_t qmp = q - p;
float u = Cross(qmp, r) / rxs;
float t = Cross(qmp, s) / rxs;
if (0.0f <= u && u < shortest_u && 0.0f <= t && t <= 1.0f) {
shortest_u = u;
}
}
}
return v + (shortest_u - 2 * std::numeric_limits<float>::epsilon()) * d;
}
size_t VdpTag::ActiveBeam(const vector_t& v) const {
float angle = AngleTo(vector_t(1.0f, 0.0f), v);
while (angle <= 0.0f) {
angle += 2 * PI;
}
size_t x = static_cast<size_t>(lround(ceilf(8 * angle / (2 * PI))) - 1);
return std::max(static_cast<size_t>(0), std::min(static_cast<size_t>(7), x));
}
template <bool compute_log_prob>
std::tuple<VdpTag, float, VdpTag::Observation, float> VdpTag::Step(
const VdpTag::Action& action, const VdpTag::Observation* observation) const {
if (_is_terminal) { throw std::logic_error("Cannot step terminal simulation."); }
VdpTag next_sim = *this;
float reward = 0;
/* ====== Step 1: Update state. ====== */
next_sim.ego_agent_position = BarrierStop(
next_sim.ego_agent_position,
AGENT_SPEED * DELTA * vector_t(1, 0).rotated(action.angle));
for (size_t i = 0; i < RK4_STEP_ITER; i++) {
next_sim.exo_agent_position = Rk4Step(next_sim.exo_agent_position);
}
next_sim.exo_agent_position.x += std::normal_distribution<float>(0.0, POS_STD)(RngDet());
next_sim.exo_agent_position.y += std::normal_distribution<float>(0.0, POS_STD)(RngDet());
next_sim.step++;
// Check terminal and rewards.
if ((next_sim.ego_agent_position - next_sim.exo_agent_position).norm() < TAG_RADIUS) {
reward = TAG_REWARD;
next_sim._is_terminal = true;
} else {
reward = STEP_REWARD;
}
if (action.look) {
reward += ACTIVE_MEAS_REWARD;
}
if (!_is_terminal) {
if (next_sim.step == MAX_STEPS) {
next_sim._is_terminal = true;
next_sim._is_failure = true;
}
}
/* ====== Step 2: Generate observation. ====== */
Observation new_observation;
if (observation) {
new_observation= *observation;
}
float log_prob = 0;
vector_t rel_pos = next_sim.exo_agent_position - next_sim.ego_agent_position;
float dist = rel_pos.norm();
size_t active_beam = ActiveBeam(rel_pos);
if (action.look) {
if (!observation) {
new_observation.beam_distances[active_beam] = std::normal_distribution<float>(dist, ACTIVE_MEAS_STD)(RngDet());
}
if constexpr (compute_log_prob) {
log_prob += NormalLogProb(dist, ACTIVE_MEAS_STD, new_observation.beam_distances[active_beam]);
}
} else {
if (!observation) {
new_observation.beam_distances[active_beam] = std::normal_distribution<float>(dist, MEAS_STD)(RngDet());
}
if constexpr (compute_log_prob) {
log_prob += NormalLogProb(dist, MEAS_STD, new_observation.beam_distances[active_beam]);
}
}
for (size_t i = 0; i < new_observation.beam_distances.size(); i++) {
if (i != active_beam) {
if (!observation) {
new_observation.beam_distances[i] = std::normal_distribution<float>(1.0, MEAS_STD)(RngDet());
}
if constexpr (compute_log_prob) {
log_prob += NormalLogProb(1.0, MEAS_STD, new_observation.beam_distances[i]);
}
}
}
return std::make_tuple(next_sim, reward, observation ? Observation() : new_observation, log_prob);
}
template std::tuple<VdpTag, float, VdpTag::Observation, float> VdpTag::Step<true>(
const VdpTag::Action& action, const VdpTag::Observation* observation) const;
template std::tuple<VdpTag, float, VdpTag::Observation, float> VdpTag::Step<false>(
const VdpTag::Action& action, const VdpTag::Observation* observation) const;
/* ====== Serialization functions ====== */
void VdpTag::Encode(list_t<float>& data) const {
ego_agent_position.Encode(data);
exo_agent_position.Encode(data);
}
cv::Mat VdpTag::Render(const list_t<VdpTag>& belief_sims) const {
constexpr float SCENARIO_MIN = -7.0f;
constexpr float SCENARIO_MAX = 7.0f;
constexpr float RESOLUTION = 0.02f;
auto to_frame = [&](const vector_t& vector) {
return cv::Point{
static_cast<int>((vector.x - SCENARIO_MIN) / RESOLUTION),
static_cast<int>((SCENARIO_MAX - vector.y) / RESOLUTION)
};
};
auto to_frame_dist = [&](float d) {
return static_cast<int>(d / RESOLUTION);
};
cv::Mat frame(
static_cast<int>((SCENARIO_MAX - SCENARIO_MIN) / RESOLUTION),
static_cast<int>((SCENARIO_MAX - SCENARIO_MIN) / RESOLUTION),
CV_8UC3,
cv::Scalar(255, 255, 255));
for (vector_t dir : list_t<vector_t>{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) {
cv::line(
frame,
to_frame(0.2f * dir),
to_frame(3.0f * dir), cv::Scalar(0, 0, 0), 1, cv::LINE_AA);
}
cv::circle(frame, to_frame(exo_agent_position), to_frame_dist(TAG_RADIUS),
cv::Scalar(0, 255, 0), -1, cv::LINE_AA);
for (const simulations::VdpTag& sim : belief_sims) {
cv::drawMarker(frame, to_frame(sim.exo_agent_position),
cv::Scalar(0, 0, 0), cv::MARKER_TILTED_CROSS, static_cast<int>(to_frame_dist(VdpTag::TAG_RADIUS) * 0.2f), 2, cv::LINE_AA);
}
cv::circle(frame, to_frame(ego_agent_position), to_frame_dist(TAG_RADIUS),
cv::Scalar(255, 0, 0), -1, cv::LINE_AA);
for (vector_t dir : list_t<vector_t>{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) {
cv::line(
frame,
to_frame(0.2f * dir),
to_frame(3.0f * dir), cv::Scalar(255, 255, 255), 1, cv::LINE_AA);
}
return frame;
}
}
| true |
202499436f7f0df49d68794749699a7f5af793fe
|
C++
|
kalokshukla/Boggle
|
/Boggle.cpp
|
UTF-8
| 10,968 | 2.984375 | 3 |
[] |
no_license
|
/*
* File: Boggle.cpp
* ----------------
* Created by Alok K Shukla on July 4th 2012
* Copyright (C) 2012 MNNIT Allahabad.
*
* This code simulates playing of classic "Boggle" word building game.
* Objective of this project is to effectively use recursive strategies.
*
*/
#include <iostream>
#include "gboggle.h"
#include "graphics.h"
#include "grid.h"
#include "lexicon.h"
#include "random.h"
#include "simpio.h"
using namespace std;
/* English Lexicon, to check for meaningful words. */
Lexicon english("EnglishWords.dat");
/* Constants */
const int BOGGLE_WINDOW_WIDTH = 650;
const int BOGGLE_WINDOW_HEIGHT = 350;
/* Size of the boggle board*/
int size;
/* The set of words selected by computer */
Set<string> allwords;
/* Set of co-ordinates on board for computer(mypaths) and player(paths)*/
/* Used to rule out returning on same path while recursing. */
Set<string> mypaths;
Set<string> paths;
/* Default configurations for board. */
const string STANDARD_CUBES[16] = {
"AAEEGN", "ABBJOO", "ACHOPS", "AFFKPS",
"AOOTTW", "CIMOTU", "DEILRX", "DELRVY",
"DISTTY", "EEGHNW", "EEINSU", "EHRTVW",
"EIOSST", "ELRTTY", "HIMNQU", "HLNNRZ"
};
const string BIG_BOGGLE_CUBES[25] = {
"AAAFRS", "AAEEEE", "AAFIRS", "ADENNN", "AEEEEM",
"AEEGMU", "AEGMNN", "AFIRSY", "BJKQXZ", "CCNSTW",
"CEIILT", "CEILPT", "CEIPST", "DDLNOR", "DDHNOT",
"DHHLOR", "DHLNOR", "EIIITT", "EMOTTT", "ENSSSU",
"FIPRSY", "GORRVW", "HIPRRY", "NOOTUW", "OOOTTU"
};
/* The strings that will contain actual contents of the board, i.e the characters which are shown. */
char boggle[5][5];
/* Function prototypes */
void welcome();
void giveInstructions();
void initRandomBoard();
void initConfBoard();
void humansTurn();
void addWords(string prefix,int i, int j);
void myTurn();
bool wordOnTheBoard(string word);
bool wordThatStartsHere(string word, int row, int col);
/* Main program */
int main() {
initGraphics(BOGGLE_WINDOW_WIDTH, BOGGLE_WINDOW_HEIGHT);
welcome();
giveInstructions();
humansTurn();
return 0;
}
/*
* Function: welcome
* Usage: welcome();
* -----------------
* Print out a cheery welcome message.
*/
void welcome() {
cout << "Welcome! You're about to play an intense game ";
cout << "of mind-numbing Boggle. The good news is that ";
cout << "you might improve your vocabulary a bit. The ";
cout << "bad news is that you're probably going to lose ";
cout << "miserably to this little dictionary-toting hunk ";
cout << "of silicon. If only YOU had a gig of RAM..." << endl << endl;
}
/*
* Function: giveInstructions
* Usage: giveInstructions();
* --------------------------
* Print out the instructions for the user.
*/
void giveInstructions() {
cout << endl;
cout << "The boggle board is a grid onto which I ";
cout << "I will randomly distribute cubes. These ";
cout << "6-sided cubes have letters rather than ";
cout << "numbers on the faces, creating a grid of ";
cout << "letters on which you try to form words. ";
cout << "You go first, entering all the words you can ";
cout << "find that are formed by tracing adjoining ";
cout << "letters. Two letters adjoin if they are next ";
cout << "to each other horizontally, vertically, or ";
cout << "diagonally. A letter can only be used once ";
cout << "in each word. Words must be at least four ";
cout << "letters long and can be counted only once. ";
cout << "You score points based on word length: a ";
cout << "4-letter word is worth 1 point, 5-letters ";
cout << "earn 2 points, and so on. After your puny ";
cout << "brain is exhausted, I, the supercomputer, ";
cout << "will find all the remaining words and double ";
cout << "or triple your paltry score." << endl << endl;
cout << "Hit return when you're ready...";
getLine();
}
/*
* Function: initRandomBoard
* Usage: initRandomBoard();
* --------------------------
* Initializes the boggle board for user using default cubes; if user wishes so.
*
*/
void initRandomBoard(){
drawBoard(size, size);
string big_boggle[25],small_boggle[16];
if (size==5) {
for (int i=0; i<25; i++) {
big_boggle[i]=BIG_BOGGLE_CUBES[i];
}
for (int i=0; i<25; i++) {
int r=randomInteger(i, 24);
string temp=big_boggle[r];
big_boggle[r]=big_boggle[i];
big_boggle[i] = temp;
}
int k=0;
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
char ch=big_boggle[k][randomInteger(0, 5)];
labelCube(i, j, ch);
boggle[i][j]=ch;
k++;
}
}
}
else {
for (int i=0; i<16; i++) {
small_boggle[i]=STANDARD_CUBES[i];
}
for (int i=0; i<16; i++) {
int r=randomInteger(i, 15);
string temp=small_boggle[r];
small_boggle[r]=small_boggle[i];
small_boggle[i] = temp;
}
int k=0;
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
char ch=small_boggle[k][randomInteger(0, 4)];
labelCube(i, j, ch);
boggle[i][j]=ch;
k++;
}
}
}
return;
}
/*
* Function: initConfBoard
* Usage: initConfBoard();
* --------------------------
* Initializes the boggle board for user using user-defined cubes; if user wishes so.
*
*/
void initConfBoard(){
cout<<"Please enter board size i.e 4 or 5: ";
size=getInteger();
drawBoard(size, size);
char ch;
cout<<"\nNow enter charcters in following format (row-major). \n\n";
cout<<" a b c d \n";
cout<<" s r r e \n";
cout<<" a e t y \n";
cout<<" w e g h \n";
cout<<"\n*****************************************************\n";
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
cin>>ch;
labelCube(i, j, ch);
boggle[i][j]=ch;
}
}
return;
}
/*
* Function: humansTurn
* Usage: humansTurn();
* --------------------------
* Lets the player choose words and accordingly updates his scores.
*
*/
void humansTurn(){
Set<string> words;
cout<<"\n\nIf you'd like to configure board for you, enter \"C/c\" else press ENTER.\n";
string s=getLine();
if (s=="C"||s=="c") {
initConfBoard();
}
else {
cout<<"Would you like a 4x4 board or 5x5? Choose 4/5: ";
cin>>size;
initRandomBoard();
}
cout<<"\nNow enter the words that you can think of as long as you like. When exhausted, enter \"I QUIT\"\n\n or simply a BLANK line.";
getchar();
string word;
while(true){
word=getLine();
if (word=="I QUIT"||word=="") {
cout<<"\nSo! now its my turn.\n";
myTurn();
break;
}
else {
paths.clear();
if (word.size()>=4&&english.contains(word)&&wordOnTheBoard(word)) {
if (!words.contains(word)) {
words.add(word);
recordWordForPlayer(word, HUMAN);
}
else {
cout<<"You are not supposed to repeat words.\n";
}
}
else {
cout<<"\nIllegal word!\n";
continue;
}
}
}
return;
}
/*
* Function: wordOnTheBoard
* Usage: wordOnTheBoard(string word);
* --------------------------
* Decides if the user chosen word is a valid word according to Boggle rules.
*
*/
bool wordOnTheBoard(string word){
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
if (boggle[i][j]==word[0]) {
if (wordThatStartsHere(word, i, j)) {
return true;
}
continue ;
}
}
}
return false;
}
/*
* Function: wordThatStartsHere
* Usage: wordThatStartsHere(string word, int row, int col);
* --------------------------
* Helper for wordOnTheBoard.
*
*/
bool wordThatStartsHere(string word, int row, int col){
if (word=="") {
foreach(string s in paths){
highlightCube(stringToInteger(s.substr(1,1)), stringToInteger(s.substr(3,1)), true);
}
return true;
}
else if(row>=size||col>=size||row<0||col<0){
return false;
}
else {
if (boggle[row][col]==word[0]) {
string path="("+integerToString(row)+","+integerToString(col)+")";
if (!paths.contains(path)) {
paths.add(path);
}
else {
return false;
}
return (wordThatStartsHere(word.substr(1), row+1, col)||wordThatStartsHere(word.substr(1), row, col+1)||wordThatStartsHere(word.substr(1), row+1, col+1)||wordThatStartsHere(word.substr(1), row-1, col)||wordThatStartsHere(word.substr(1), row, col-1)||wordThatStartsHere(word.substr(1), row-1, col-1)||wordThatStartsHere(word.substr(1), row-1, col+1)||wordThatStartsHere(word.substr(1), row+1, col-1));
}
else {
return false;
}
}
}
/*
* Function: myTurn
* Usage: myTurn();
* --------------------------
* Plays the computer's part.
*
*/
void myTurn(){
Set<string> modified;
string s;
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
s[0]=boggle[i][j];
mypaths.clear();
addWords(s, i, j);
}
}
foreach(string word in allwords){
recordWordForPlayer(word, COMPUTER);
}
return;
}
/*
* Function: addWords
* Usage: addWords(string prefix,int i, int j;
* --------------------------
* Adds valid words for computer.
*
*/
void addWords(string prefix,int i, int j){
if (i<0||i>=size||j<0||j>=size||(!english.containsPrefix(prefix))) {
return;
}
else {
if (english.contains(prefix)&&prefix.size()>=4) {
allwords+=prefix;
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
highlightCube(i, j, false);
}
}
}
string path="("+integerToString(i)+","+integerToString(j)+")";
if (!mypaths.contains(path)) {
mypaths.add(path);
}
else {
return;
}
addWords(prefix+boggle[i-1][j], i-1, j);
addWords(prefix+boggle[i-1][j+1], i-1, j+1);
addWords(prefix+boggle[i-1][j-1], i-1, j-1);
addWords(prefix+boggle[i][j+1], i, j+1);
addWords(prefix+boggle[i][j-1], i, j-1);
addWords(prefix+boggle[i+1][j+1], i+1, j+1);
addWords(prefix+boggle[i+1][j], i+1, j);
addWords(prefix+boggle[i+1][j-1], i+1, j-1);
}
}
| true |
b346498faeca2e0e10850997b768de73f5bd14d9
|
C++
|
davo16dev/my_coj_solutios
|
/JDkaka-p3757-Accepted-s1096604.cpp
|
UTF-8
| 625 | 2.953125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
void cantDiv(int n){
int imp = 1;
int sol = 1;
for(int i = 2; i * i <= n; i++){
int e = 0;
while(n % i == 0){
e++;
n /= i;
}
sol *= (e + 1);
if(i & 1){
imp *= (e + 1);
}
}
if(n > 1){
sol *= 2;
imp *= 2;
}
cout << "P: "<< sol - imp << " I: " << imp << "\n";;
//return sol - imp;
}
int main()
{
//out << cantDiv(4) << endl;
int t;
cin >> t;
while(t--){
int n;
cin >> n;
cantDiv(n);
}
return 0;
}
| true |
32934437edbe9f72b76422aa5099b58f2488e94c
|
C++
|
denghc/danmugame
|
/RSEngine/TextureManager.cpp
|
UTF-8
| 1,672 | 2.984375 | 3 |
[] |
no_license
|
#include "TextureManager.h"
#include "TextureClass.h"
#include "GraphicsClass.h"
TextureManager* TextureManager::m_instance = 0;
TextureManager::TextureManager(void)
{
}
TextureManager::~TextureManager(void)
{
}
void TextureManager::Initialize()
{
this->m_textureList.clear();
}
void TextureManager::Shutdown()
{
for (std::vector<TextureClass*>::iterator iter = this->m_textureList.begin(); iter != this->m_textureList.end(); ++iter)
{
TextureClass* rob = *iter;
rob->Shutdown();
}
this->m_textureList.clear();
}
void TextureManager::InsertTexture(TextureClass* tc)
{
this->m_textureList.push_back(tc);
}
void TextureManager::RemoveTexture(TextureClass* rob)
{
for (std::vector<TextureClass*>::iterator iter = this->m_textureList.begin(); iter != this->m_textureList.end(); ++iter)
{
if (rob == *iter)
{
this->m_textureList.erase(iter);
return;
}
}
}
TextureClass* TextureManager::GetTexture(const char* textureName)
{
for (std::vector<TextureClass*>::iterator iter = this->m_textureList.begin(); iter != this->m_textureList.end(); ++iter)
{
if ((*iter)->NameEqual(textureName))
{
return (*iter);
}
}
return NULL;
}
/*
create a texture from file
or if the texture already exists
just return
*/
void TextureManager::CreateAndInsertTexture(const char* fileName)
{
for (std::vector<TextureClass*>::iterator iter = this->m_textureList.begin(); iter != this->m_textureList.end(); ++iter)
{
if ((*iter)->NameEqual(fileName))
{
return;// already exists
}
}
//else create
TextureClass* tc = new TextureClass();
tc->Initialize(GraphicsClass::m_D3D->GetDevice(), (char*)fileName);
m_textureList.push_back(tc);
}
| true |
228597942b8b3c2f016024789d47c6bd0f979658
|
C++
|
grant-h/gfx
|
/engine_template/CameraObject.hpp
|
UTF-8
| 1,255 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef _CAMERA_OBJECT_HPP
#define _CAMERA_OBJECT_HPP
#include <glm/glm.hpp>
#include <memory>
#include <string>
#include <SceneObject.hpp>
class CameraObject : public SceneObject {
public:
CameraObject(const char * name);
virtual ~CameraObject();
void position(glm::vec3 & pos) override;
void position(float x, float y, float z) override;
virtual glm::vec3 position() override { return SceneObject::position(); }
glm::vec3 get_eye() { return camera_eye_; }
glm::mat4 get_view_matrix();
glm::mat4 get_projection_matrix();
void set_fov(float fov); // in degrees
void set_near_clip(float near);
void set_far_clip(float far);
void set_aspect_ratio(float aspect);
void set_yaw(float yaw) { yaw_ = yaw; }
void set_pitch(float pitch) { pitch_ = pitch; }
float get_yaw() { return yaw_; }
float get_pitch() { return pitch_; }
virtual bool init() override;
virtual void tick() override;
virtual void draw(SceneRenderer *) override;
private:
void calculate_view();
bool show_debug_camera_;
float fov_, near_, far_, aspect_ratio_;
float yaw_, pitch_;
glm::vec3 camera_eye_;
glm::mat4 view_;
glm::mat4 projection_;
};
#endif // _CAMERA_OBJECT_HPP
| true |
87adf5446e63df21ea7f38f6cf9a4c0575d1c0d7
|
C++
|
Phu-Mine/ArduinoHeroLive
|
/Stepper/Ramp15_Test/Ramp15_Test.ino
|
UTF-8
| 2,059 | 2.953125 | 3 |
[] |
no_license
|
// Control stepper speed from an Arduino UNO.
//X
int enX = 38 ;
int dirPinX = A1 ;
int stepPinX = A0 ;
//Y
int enY = A2 ;
int dirPinY = A7 ;
int stepPinY = A6 ;
//Z
int enZ = A8 ;
int dirPinZ = 48 ;
int stepPinZ = 46 ;
//E0
int enE0 = 24 ;
int dirPinE0 = 28 ;
int stepPinE0 = 26 ;
//E1
int enE1 = 30 ;
int dirPinE1 = 34 ;
int stepPinE1 = 36 ;
long pulsePerRound = 200; // so xung/vong
void setup()
{
Serial.begin(9600);
pinMode(enX, OUTPUT); // Enable
pinMode(enY, OUTPUT);
pinMode(enZ, OUTPUT);
pinMode(enE0, OUTPUT);
pinMode(enE1, OUTPUT);
pinMode(stepPinX, OUTPUT); // Step
pinMode(stepPinY, OUTPUT);
pinMode(stepPinZ, OUTPUT);
pinMode(stepPinE0, OUTPUT);
pinMode(stepPinE1, OUTPUT);
pinMode(dirPinX, OUTPUT); // Dir
pinMode(dirPinY, OUTPUT);
pinMode(dirPinZ, OUTPUT);
pinMode(dirPinE0, OUTPUT);
pinMode(dirPinE1, OUTPUT);
digitalWrite(enX, LOW); // Set Enable low
digitalWrite(enY, LOW);
digitalWrite(enZ, LOW);
digitalWrite(enE0, LOW);
digitalWrite(enE1, LOW);
}
void loop() {
moving(5, stepPinX, dirPinX, LOW); // move 5 round
delay(200);
moving(5, stepPinX, dirPinX, HIGH); // move 5 round
delay(500);
moving(5, stepPinY, dirPinY, LOW); //move 5 round
delay(200);
moving(5, stepPinY, dirPinY, HIGH); //move 5 round
delay(500);
moving(5, stepPinZ, dirPinZ, LOW); //move 10 round
delay(200);
moving(5, stepPinZ, dirPinZ, HIGH); //move 10 round
delay(500);
moving(5, stepPinE0, dirPinE0, LOW); //move 10 round
delay(100);
moving(5, stepPinE0, dirPinE0, HIGH); //move 10 round
delay(500);
moving(5, stepPinE1, dirPinE1, LOW); //move 10 round
delay(200);
moving(5, stepPinE1, dirPinE1, HIGH); //move 10 round
delay(500);
delay(5000);
}
//moving n round;
void moving(int n, int stepPin, int dirPin, bool dir) {
long stepsCount = 0;
long totalPulse = n * pulsePerRound;
digitalWrite(dirPin, dir);
while (stepsCount < totalPulse) {
stepsCount++;
digitalWrite(stepPin, HIGH);
delay(1);
digitalWrite(stepPin, LOW);
delay(5);
}
}
| true |
e6af434b85d8fdca6771e44891b9dbb9dc814838
|
C++
|
LorenzM/Converter
|
/Picture/Picture.cpp
|
ISO-8859-1
| 2,874 | 3.03125 | 3 |
[] |
no_license
|
#include "Picture.h"
Picture::Picture(string file="Ouran.ppm", int step=16){
fileName=file;
boost::iostreams::mapped_file mmap(fileName, boost::iostreams::mapped_file::readonly);
pointer_mmap = mmap.const_data();
mmap_length = pointer_mmap + mmap.size();
this->step=step;
setPicPara();
FFillStructureWithPicInfo();
cout << "Pixel 0, 1718: " << matrix_Red[1717] <<" ";
cout << matrix_Green[1717]<<" ";
cout << matrix_Blue[1717];
};
Picture::~Picture(){
};
void Picture::setPicPara(){
int i=0;
//skip first tow lines
while (i<2){
if ((pointer_mmap = static_cast<const char*>(memchr(pointer_mmap, '\n', mmap_length -pointer_mmap)))){
i++;
++pointer_mmap;
}
}
//const char index= *pointer_mmap;
/*string width, height;
while (!isspace(*pointer_mmap) ){//lese bis zu space
width+=*pointer_mmap;
pointer_mmap++;
}
while (isspace(*pointer_mmap)){//skip space
*pointer_mmap;
pointer_mmap++;
}
while(!isspace(*pointer_mmap)){
height+=*pointer_mmap;
pointer_mmap++;
}
while (isspace(*pointer_mmap)){//skip space
*pointer_mmap;
pointer_mmap++;
}*/
this->width= readSingleValue();// atoi(width.c_str());
this->height= readSingleValue();//atoi(height.c_str());
this->maxColorValue=readSingleValue();
cout <<"Width: " << this->width << "Height: " << this->height<< " Color: "<< maxColorValue <<endl;
setFrame();
}
void Picture::setFrame(){
if((width>step) & (width % step == 0)){
width_frame=width;
}
else if ((width>step) & (width % step != 0)){
width_frame=(width/step+1)*step;
}
if((height>step) & (height % step == 0)){
height_frame=width;
}
else if ((height>step) & (height % step != 0)){
height_frame=(height/step+1)*step;
}
};
void Picture::FFillStructureWithPicInfo(){
matrix_Red= valarray<int> (height_frame*width_frame); // hier kein array damit spter slice mglich ist!!
matrix_Green= valarray<int> (height_frame*width_frame);
matrix_Blue=valarray<int> (height_frame*width_frame);
for(int i=0;i<height_frame;i++){
for(int j=0;j<width_frame;j++){
if(j<width){
matrix_Red[i*width_frame+j]=readSingleValue();
matrix_Green[i*width_frame+j]=readSingleValue();
matrix_Blue[i*width_frame+j]=readSingleValue();
}
else{//Farbwerte auffllen
matrix_Red[i*width_frame+j]=matrix_Red[i*width_frame+width-1];
matrix_Green[i*width_frame+j]=matrix_Green[i*width_frame+width-1];
matrix_Blue[i*width_frame+j]=matrix_Blue[i*width_frame+width-1];
}
}
}
}
int Picture::readSingleValue(){
if(!*pointer_mmap){return 0;}
string tmp;
while (!isspace(*pointer_mmap) ){//lese bis zu space
tmp+=*pointer_mmap;
pointer_mmap++;
}
while (isspace(*pointer_mmap)){//skip space
*pointer_mmap;
pointer_mmap++;
}
return atoi(tmp.c_str());
}
void main(){
Picture * pic= new Picture("Ouran.ppm");
system("pause");
delete pic;
}
| true |
a80963e8ae1832b0868c283ebda7c298bc302f0d
|
C++
|
rishabh-live/oop-w-cpp-4-sem
|
/Labs/Lab 2/q3_c.cpp
|
UTF-8
| 385 | 2.6875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter Grid Size: ";
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<"+-----";
}
cout<<"+"<<endl;
for(int j=1;j<=3;j++)
{
for(int k=1;k<=n;k++)
{
cout<<"| ";
}
cout<<"|"<<endl;
}
}
for(int j=1;j<=n;j++)
{
cout<<"+-----";
}
cout<<"+"<<endl;
return 0;
}
| true |
05c447fd22667365f017878824eef98b6a2e40ba
|
C++
|
HScarb/CPPLearn
|
/CPP5_10-2_14.12.21/CPP5_10-2_14.12.21/源.cpp
|
UTF-8
| 839 | 3.421875 | 3 |
[] |
no_license
|
#include<iostream>
#include<iomanip>
#include<string>
#include<cstring>
using namespace std;
class Person
{
public:
Person(){ lname = ""; fname[0] = '\0'; }
Person(const string & ln, const char * fn = "Heyyou") //#2
{
lname = ln;
strcpy(fname, fn);
}
void Show()const; //firstname lastname format
void FormalShow()const; //lastname, firstname format
private:
static const int LIMIT = 25;
string lname; //Person's last name
char fname[LIMIT]; //Person's first name
};
void Person::Show()const
{
cout << fname << " " << lname << endl;
}
void Person::FormalShow()const
{
cout << lname << ", " << fname << endl;
}
int main()
{
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
one.Show();
one.FormalShow();
two.Show();
two.FormalShow();
three.Show();
three.FormalShow();
system("pause");
}
| true |
3b379fc15f9a8c7e4f3e449801351068c6b541c6
|
C++
|
neurovertex/graphshell
|
/core/box.cpp
|
UTF-8
| 4,764 | 2.78125 | 3 |
[] |
no_license
|
#include "graphshell.h"
#include "sockets/controlsockets.h"
namespace graphshell {
using namespace graphshell::sockets;
/*!
* \brief Creates a new Box, adds the general input (start, stop) and output (started, stopped) control (signal) sockets.
* \param typeName Box::typeName
* \param autostart Box::autostart
*/
Box::Box(QString typeName, bool autostart) :
QThread()
{
this->typeName = typeName;
setObjectName(typeName);
this->autostart = autostart;
shell = nullptr;
InputSignalSocket *start = new InputSignalSocket(DataType::getType("/signal/"), "start");
InputSignalSocket *stop = new InputSignalSocket(DataType::getType("/signal/"), "stop");
OutputSignalSocket *started = new OutputSignalSocket(DataType::getType("/signal/void/"), "started", false, new QVariant());
OutputSignalSocket *stopped = new OutputSignalSocket(DataType::getType("/signal/void/"), "stopped", false, new QVariant());
connect(start, &InputSignalSocket::valueReceived, this, &Box::startBox);
connect(stop, &InputSignalSocket::valueReceived, this, &Box::stopBox);
connect(this, &Box::started, started, &OutputSignalSocket::sendVoid);
connect(this, &Box::finished, stopped, &OutputSignalSocket::sendVoid);
addSocket(*start, CONTROL);
addSocket(*stop, CONTROL);
addSocket(*started, CONTROL);
addSocket(*stopped, CONTROL);
}
/*!
* \brief Sets this Box's parent shell to the given GraphSell. Note that, for threading
* reasons, this will not call QObject::setParent(). This causes a fatal error if the Box
* already had a parent.
* \param shell The new parent.
*/
void Box::setParent(GraphShell &shell)
{
if (this->shell == nullptr)
this->shell = &shell;
else if (this->shell == &shell)
qWarning() << "Box "<< objectName() <<"'s parent has already been set";
else
qFatal("Cannot change a box's parent");
}
Box::~Box()
{
}
void Box::startBox() {
qDebug() << this << " start requested";
moveToThread(this);
this->start();
}
void Box::stopBox() {
qDebug() << this << " stop requested";
this->exit();
}
// ############ ADD ##############
void Box::addInputSocket(InputSocket &socket, unsigned int flags)
{
QHash<QString, InputSocket*> &map = ((flags&Box::DATA) > 0 ? dataInput: controlInput);
if (map.value(socket.objectName()) == &socket) {
qWarning() << "Socket "<< &socket <<" has already been added to its parent box";
} else {
if (map.contains(socket.objectName())) {
removeSocket(*map[socket.objectName()], flags);
}
map[socket.objectName()] = &socket;
socket.setParent(*this);
emit socketAdded(socket, flags);
}
}
void Box::addOutputSocket(OutputSocket &socket, unsigned int flags)
{
QHash<QString, OutputSocket*> &map = ((flags&Box::DATA) > 0 ? dataOutput : controlOutput);
if (map.value(socket.objectName()) == &socket) {
qWarning() << "Socket "<< &socket <<" has already been added to its parent box";
} else {
if (map.contains(socket.objectName())) {
removeSocket(*map[socket.objectName()], flags);
}
map[socket.objectName()] = &socket;
socket.setParent(*this);
emit socketAdded(socket, flags);
}
}
/*!
* \brief Removes a socket from the box according to flags. The socket is deleted after this.
* \param sock the Socket to add
* \param flags sets whether the socket is data (Box::DATA) or control (Box::CONTROL).
* Box::INPUT and Box::OUTPUT flags are ignored and deduced from Socket::isInput()
* \return true if the socket was successfully removed (i.e if it was actually present)
*/
bool Box::removeSocket(Socket &sock, unsigned int flags)
{
if (sock.isInput())
return removeInputSocket((InputSocket&)sock, (flags | INPUT) & ~OUTPUT);
else
return removeOutputSocket((OutputSocket&)sock, (flags | OUTPUT) & ~INPUT);
delete &sock;
}
bool Box::removeInputSocket(InputSocket &socket, unsigned int flags)
{
QHash<QString, InputSocket*> &map = ((flags&Box::DATA) > 0 ? dataInput : controlInput);
if (!map.contains(socket.objectName()))
qWarning() << "Attempt at removing an absent socket";
else {
map.remove(socket.objectName());
emit socketRemoved(socket);
return true;
}
return false;
}
bool Box::removeOutputSocket(OutputSocket &socket, unsigned int flags)
{
QHash<QString, InputSocket*> &map = ((flags&Box::DATA) > 0 ? dataInput : controlInput);
if (!map.contains(socket.objectName()))
qWarning() << "Attempt at removing an absent socket";
else {
map.remove(socket.objectName());
emit socketRemoved(socket);
return true;
}
return false;
}
}
| true |
cc4e8690afb3ba1f2489c65a167f09b190fca2d6
|
C++
|
JIbald/Doorman_raspberry
|
/src/eyes_servos.cpp
|
UTF-8
| 1,975 | 2.90625 | 3 |
[] |
no_license
|
// #include <wiringPi.h>
// #include <stdio.h>
// #include <stdlib.h>
// #include <stdint.h>
// int main (void)
// {
// int bright ;
// printf ("Raspberry Pi wiringPi PWM test program\n") ;
// if (wiringPiSetup () == -1)
// exit (1) ;
// pinMode (1, PWM_OUTPUT) ;
// for (;;)
// {
// for (bright = 0 ; bright < 1024 ; ++bright)
// {
// pwmWrite (1, bright) ;
// delay (1) ;
// }
// for (bright = 1023 ; bright >= 0 ; --bright)
// {
// pwmWrite (1, bright) ;
// delay (1) ;
// }
// }
// if (wiringPiSetup () == -1) //using wPi pin numbering
// {
// exit (1);
// }
// pinMode(1, PWM_OUTPUT);
// pwmSetMode(PWM_MODE_MS);
// pwmSetClock(384); //clock at 50kHz (20us tick)
// pwmSetRange(1000); //range at 1000 ticks (20ms)
// pwmWrite(1, 75); //theretically 50 (1ms) to 100 (2ms) on my servo 30-130 works ok
// return 0 ;
// }
#include <wiringPi.h>
#include <stdio.h>
//eye position (right / left) as if your own eyes
int main (void)
{
printf ("Raspberry Pi wiringPi test program\n");
wiringPiSetupGpio();
pinMode (18, PWM_OUTPUT); //left eye horizontal movement
pinMode (24, PWM_OUTPUT); //left eye vertical movement
pwmSetMode (PWM_MODE_MS);
pwmSetClock(384); //clock at 50kHz (20us tick)
pwmSetRange (2000);
pwmSetClock (192);
//look left, delay
printf ("look left, delay\n");
pwmWrite(18, 540);
delay(1000);
//look right, delay
printf ("look right, delay\n");
pwmWrite(18, 240);
delay(1000);
//look middle, delay
printf ("look middle\n");
pwmWrite(18, 420);
delay(1000);
// //look up, delay
// printf ("look up\n");
// pwmWrite(24, 300);
// delay(1000);
// //look down, delay
// printf ("look down\n");
// pwmWrite(24, 420);
// delay(1000);
// //look middle, delay
// printf("look middle\n");
// pwmWrite(24, 500);
// delay(1000);
printf("end of program.\n");
return 0;
}
| true |
78a798b97162356262e51b3e0aaa4d9c666c457b
|
C++
|
SharktasticA/Demo-SearchAlgorithms
|
/Source.cpp
|
UTF-8
| 604 | 2.8125 | 3 |
[] |
no_license
|
#include "NodeLoader.h"
#include "BFS.h"
#include "DFS.h"
#include "Dijkstra.h"
using namespace std;
int main(void)
{
try
{
NodeLoader nL("Map.txt");
vector<Node*> map = nL.GetNodes();
BFS bfsAl(map, "Andor", "Tau Ceti");
string path = bfsAl.Run();
cout << "BFS result:\n" << path << endl;
DFS dfsAl(map, "Andor", "Tau Ceti");
path = dfsAl.Run();
cout << "DFS result:\n" << path << endl;
Dijkstra dijkstraAl(map, "Andor", "Tau Ceti");
path = dijkstraAl.Run();
cout << "Dijkstra result:\n" << path << endl;
}
catch (char* msg)
{
cout << msg;
}
Utility::pause();
return 0;
}
| true |
ed4b8ce08bd914b04e519a8719d48fe391a1c82e
|
C++
|
chanhx/PAT
|
/1090/1090.cc
|
UTF-8
| 1,328 | 3.25 | 3 |
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
void BFS(const vector<vector<int>> &tree,
int root,
double p,
const double r,
double &highest_price,
int &count)
{
highest_price = 0;
count = 0;
queue<int> q;
q.push(root);
while (!q.empty()) {
for (int i = 0, size = q.size(); i < size; ++i) {
auto s = q.front();
q.pop();
if (tree[s].size() == 0) {
if (p > highest_price) {
highest_price = p;
count = 1;
} else if (p == highest_price) {
++count;
}
}
for (auto ss : tree[s]) {
q.push(ss);
}
}
p *= r;
}
}
int main()
{
int n;
double p, r;
scanf("%d %lf %lf", &n, &p, &r);
vector<vector<int>> tree(n);
int root;
for (int i = 0; i < n; ++i) {
int supplier;
scanf("%d", &supplier);
if (supplier == -1) {
root = i;
} else {
tree[supplier].push_back(i);
}
}
double highest_price;
int count;
BFS(tree, root, p, 1+r/100, highest_price, count);
printf("%.2f %d\n", highest_price, count);
return 0;
}
| true |
e9e7ddbf55291263ff282dec50e19b4a6c5875ad
|
C++
|
wangrui22/haze
|
/AIGames/Include/Core/ortho_camera.h
|
UTF-8
| 1,247 | 2.59375 | 3 |
[] |
no_license
|
#ifndef ARITHMETIC_ORTHO_CAMERA_H_
#define ARITHMETIC_ORTHO_CAMERA_H_
#include "Core/camera_base.h"
#include "Core/quat4.h"
#include "Core/vector2.h"
class OrthoCamera : public CameraBase
{
public:
OrthoCamera();
OrthoCamera(double left, double right, double bottom, double top, double near, double far0);
virtual ~OrthoCamera();
void set_ortho(double left, double right, double bottom, double top, double near, double far0);
void get_ortho(double& left, double& right, double& bottom, double& top, double& near, double& far0) const;
virtual Matrix4 get_projection_matrix();
virtual Matrix4 get_view_projection_matrix();
virtual void zoom(double rate);
virtual void pan(const Vector2& pan);
double get_near_clip_distance() const;
double get_far_clip_distance() const;
OrthoCamera& operator =(const OrthoCamera& camera);
bool operator == (const OrthoCamera& camera) const;
protected:
virtual void calculate_projection_matrix_i();
private:
double _left;
double _right;
double _bottom;
double _top;
double _near;
double _far;
Matrix4 _mat_projection;
bool _is_proj_mat_cal;
//Zoom
double _ZoomFactor;
Vector2 _VecPan;
};
#endif
| true |
b3cec25156373ef6ffd7f208ef06fac3770a8290
|
C++
|
ProMoriarty/PointToOffer
|
/OJ43 N个骰子的点数.cpp
|
UTF-8
| 1,467 | 3.421875 | 3 |
[] |
no_license
|
//
// Created by ProMoriarty on 2017/9/8.
//
/**
* n个骰子的点数
* 题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为S。输入n,打印出S的所有可能的值出现的概率。
*/
//方法一:递归
// 思路:设n个骰子某次投掷点数和为s的出现次数是F(n, s),那么,F(n, s)等于n - 1个骰子投掷的点数和为
//s - 1、s - 2、s - 3、s -4、s - 5、s - 6时的次数的总和:
//F(n , s) = F(n - 1, s - 1) + F(n - 1, s - 2) + F(n - 1, s - 3) + F(n - 1, s - 4) + F(n - 1, s - 5) + F(n - 1, s - 6)。
#include <iostream>
#include <time.h>
#include <vector>
#include <assert.h>
#include <list>
#include <math.h>
using namespace std;
//计算n个骰子某次投掷点数和为s的出现次数
int CountNumber(int n, int s) {
//n个骰子点数之和范围在n到6n之间,否则数据不合法
if(s < n || s > 6*n)
return 0;
//当有一个骰子时,一次骰子点数为s(1 <= s <= 6)的次数当然是1
if(n == 1)
return 1;
else
return CountNumber(n-1, s-6) + CountNumber(n-1, s-5) + CountNumber(n-1, s-4) +
CountNumber(n-1, s-3) +CountNumber(n-1, s-2) + CountNumber(n-1, s-1);
}
void listDiceProbability(int n) {
int i=0;
unsigned int nTotal = pow((double)6, n);
for(i = n; i <= 6 * n; i++) {
printf("P(s=%d) = %d/%d\n", i, CountNumber(n,i), nTotal);
}
}
int main() {
listDiceProbability(3);
}
| true |
9aaaf3e336dd9eef4c1d7ed1ac48e172e9b93026
|
C++
|
lindobyte/cpprestapi
|
/src/resource/country/Country.cpp
|
UTF-8
| 1,214 | 2.625 | 3 |
[] |
no_license
|
#include "Country.hpp"
using namespace std;
using namespace web;
using namespace utility;
using namespace http;
using namespace web::http::experimental::listener;
Country::Country(uri_builder uri)
: Resource(uri.append_path(U("country")).to_string())
/*: Resource(uri.append_path(U("Country")).to_uri().to_string()),
getDescription(MethodDescription::type::GET),
putDescription(MethodDescription::type::PUT),
postDescription(MethodDescription::type::POST),
deleteDescription(MethodDescription::type::DELETE)*/
{
getDescription = MethodDescription(1);
}
void Country::handleGet(http_request &message)
{
ucout << message.to_string() << endl;
message.reply(status_codes::OK, "{\"key\":\"test\",\"Country\":\"tz\"}");
};
/*void Country::handle_post(http_request message)
{
ucout << message.to_string() << endl;
message.reply(status_codes::MethodNotAllowed);
};
void Country::handle_delete(http_request message)
{
ucout << message.to_string() << endl;
message.reply(status_codes::MethodNotAllowed);
};
void Country::handle_put(http_request message)
{
ucout << message.to_string() << endl;
message.reply(status_codes::MethodNotAllowed);
};*/
| true |
f9554d294da657b41f1488f3fb46f16e12758afa
|
C++
|
ningjingdemayi/zhada
|
/subway4/subway4_main.cpp
|
UTF-8
| 6,497 | 2.8125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include "Station.h"
#include "Log.h"
using namespace std;
vector<Station> stations;
vector<Log> logs;
bool stations_exist(int station_id);
void print_stations(const vector<Station> & _stations);
void print_station(const Station &station);
void load_stations(const char * filename);
long int StringtoTime(const char *str);
bool insert_logs(Log & log);
void print_logs(const vector<Log> & _logs);
void load_log(const char * fileName);
bool is_enter_line1(const int enter_station_id);
void BubbleSort(vector<Log> & logs , vector<Log>::size_type count);
int check_in60_counts(int index)
{
int counts = 0;
for(int i = index ; i < logs.size() ; i++)
{
++ counts ;
if(logs[i].enter_time > logs[index].enter_time + 60)
return counts;
}
return counts;
}
std::string timeStampToHReadble(long timestamp)
{
const time_t rawtime = (const time_t)timestamp;
struct tm * dt;
char timestr[30];
char buffer [30];
dt = localtime(&rawtime);
// use any strftime format spec here
strftime(timestr, sizeof(timestr), "%H:%M:%S", dt);
sprintf(buffer,"%s", timestr);
std::string stdBuffer(buffer);
return stdBuffer;
}
int main()
{
load_stations("subway.txt");
// load ling1 and sorted
load_log("sample.log");
unsigned int start = logs[0].enter_time;
unsigned int step = 60;
int index = 0;
vector<Log>::iterator it = logs.begin();
while(it != logs.end())
{
it->in_60_count = check_in60_counts(index);
++ index;
++ it;
}
int bigest_now = 0;
int index_now = 0;
int index2 = 0;
vector<Log>::iterator it2 = logs.begin();
while(it2 != logs.end())
{
if(it2->in_60_count > bigest_now)
{
bigest_now = it2->in_60_count;
index_now = index2;
}
++ index2;
++ it2;
}
cout << bigest_now << endl;
cout << logs[index_now].in_60_count << endl;
unsigned int start_time = logs[index_now].enter_time;
unsigned int end_time = start_time + 60;
cout << timeStampToHReadble(start_time) << " "<< timeStampToHReadble(end_time ) ;
ofstream fout("output4.txt");
fout << bigest_now << endl;
fout << timeStampToHReadble(start_time) << " "<< timeStampToHReadble(end_time ) ;
fout.close();
getchar();
return 0;
}
bool stations_exist(int station_id)
{
vector<Station>::iterator it = stations.begin();
while(it != stations.end())
{
if(it->station_id == station_id)
{
it->subways_amount ++;
return true;
}
++ it;
}
return false;
}
void print_stations(const vector<Station> & _stations)
{
vector<Station>::const_iterator it = _stations.begin();
while(it != _stations.end())
{
cout << "id:" << it->station_id
<< " name:"<< it->station_name
<< " subway_id:"<< it->subway_id
<< " subway_amount:"<< it->subways_amount << endl;
++ it;
}
}
void print_station(const Station &station)
{
cout << "id:" << station.station_id
<< " name:"<< station.station_name
<< " subway_id:"<< station.subway_id
<< " subway_amount:"<< station.subways_amount << endl;
}
void load_stations(const char * filename)
{
ifstream fin(filename);
char line[64] = {0};
string id;
string name;
Subway subway_now;
int i = 0;
while(fin.getline(line , sizeof(line)))
{
stringstream ss(line);ss >> id;ss >> name;
if(id == "") continue;
if(name == "") { subway_now.subway_id = ++i ; subway_now.subway_name = id;continue;}
Station station;
station.station_id = atoi(id.c_str());
station.subway_id = subway_now.subway_id;
station.station_name = name;
if( ! stations_exist(station.station_id))
stations.push_back(station);
//cout << id << "--" << name << endl;
id.clear();
name.clear();
}
fin.close();
//print_stations(stations);
}
long int StringtoTime(const char *str)
{
struct tm t;
int year,month,day, hour,minite,second;
sscanf(str,"%d-%d-%d %d:%d:%d",&year,&month,&day,&hour,&minite,&second);
t.tm_year = year-1900;
t.tm_mon = month;
t.tm_mday = day;
t.tm_hour = hour;
t.tm_min = minite;
t.tm_sec = second;
t.tm_isdst = 0;
time_t t_of_day;
t_of_day=mktime(&t);
long int time;
time = t_of_day;
return time;
}
bool insert_logs(Log & log)
{
vector<Log> ::iterator it = logs.begin();
while(it != logs.end())
{
if(it->user_id == log.user_id)
{
if(it->enter_time == 0)
{
it->enter_time = log.enter_time;
it->enter_station_id = log.enter_station_id;
}
if(it->out_time == 0)
{
it->out_time = log.out_time;
it->out_station_id = log.out_station_id;
}
return true;
}
++ it;
}
logs.push_back(log);// here maybe wrong
return false;
}
void print_logs(const vector<Log> & _logs)
{
vector<Log>::const_iterator it = _logs.begin();
int i = 0;
while(it != _logs.end())
{
++ i;
cout << i;
cout << " enter_time:" << it->enter_time;
cout << " user_id:" << it->user_id;
cout << " enter_station_id:" << it->enter_station_id;
//cout << " out_station_id:" << it->out_station_id;
//cout << " out_time:" << it->out_time;
cout << endl;
++ it;
}
}
bool is_enter_line1(const int enter_station_id)
{
vector<Station>::const_iterator it = stations.begin();
while(it != stations.end())
{
if(it->subway_id == 1 && enter_station_id == it->station_id)
return true;
++it;
}
return false;
}
// this time we only load enter line1
void load_log(const char *fileName)
{
ifstream fin(fileName);
string log_now_str[14];
char line[256] = {0};
cout << "loading log..." << endl;
while(fin.getline(line , sizeof(line)))
{
stringstream ss(line);
for(int i = 0 ; i < 14 ; ++ i)
{
ss >> log_now_str[i];
}
if(log_now_str[0] == "#")
continue;
Log log;
log.user_id = log_now_str[10];
stringstream sst;
sst << log_now_str[0] << " " << log_now_str[1];
string time_str = sst.str();
unsigned int time_int = StringtoTime(time_str.c_str());
if(log_now_str[4] != "entered")
continue;
log.enter_time = time_int;
log.enter_station_id = atoi(log_now_str[6].c_str());
if( !is_enter_line1(log.enter_station_id ))
continue;
insert_logs(log);
}
fin.close();
BubbleSort(logs , logs.size());
print_logs(logs);
cout << "load log success!" << endl;
}
void BubbleSort(vector<Log> & logs , vector<Log>::size_type count)
{
Log temp;
for (int i = 1; i < count; i++)
{
for (int j = count - 1; j >= i; j--)
{
if (logs[j].enter_time < logs[ j - 1 ].enter_time)
{
temp = logs[j - 1];
logs[j - 1] = logs[j];
logs[j] = temp;
}
}
}
}
| true |
acb67f369d47a2d6cca2360b4ce1e7d9ca190cd8
|
C++
|
Emrace/Intro-Programming-2015
|
/71602_Юлиана Стайкова - checked/zadacha1.cpp
|
UTF-8
| 740 | 3.21875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int pr_chislo(int num)
{
if ((num >= 7) && (num <= 39))
{
//got the idea, almost right for the task at hand - +0.3
if (((num%num == 0) && (num % 1 == 0)) && ((num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0) || (num % 7 == 0)))
return true;
else
return false;
}
else
{
cout << "Error. " << endl;
}
}
int triug_chisla(int num)
{
int k, sum=0;
//k is not initialized
if (pow(num, 1 / 3) == k)
{
for (int i = 0; i <= num; i++)
{
sum += i;
}
}
return sum;
}
// no fibonacci function: -0.5
int main()
{
//functions are not called properly: -0.5
int n, s=0;
cout << "n= ";
cin >> n;
pr_chislo(n);
triug_chisla(s);
system("pause");
return 0;
}
// 0.5\2.0
| true |
9a07346c6dfd9ccafcb7c0b527fae5a5528129b9
|
C++
|
kengonakajima/snippets
|
/cpp/cppsort/aho.cpp
|
UTF-8
| 487 | 3.40625 | 3 |
[] |
no_license
|
#include <vector>
#include <algorithm>
#include <iostream>
class X
{
public:
X(int hoge ){ v = hoge; }
int v;
};
bool operator<(const X&a, const X&b)
{
return a.v < b.v ;
}
int main()
{
X x1(10);
X x2(1);
X x3(5);
std::vector<X>v;
v.push_back(x1);
v.push_back(x2);
v.push_back(x3);
std::sort(v.begin(), v.end());
std::cout << v[0].v << "," << v[1].v << "," << v[2].v << std::endl;
}
| true |
aef6f90856de503f9d5860f7cbd98949b7188aa9
|
C++
|
frankynous/Sensoj-Project
|
/src/stars.cpp
|
UTF-8
| 1,076 | 2.90625 | 3 |
[] |
no_license
|
#include "stars.h"
stars::stars()
{
}
stars::~stars()
{
}
void stars::setup() {
quantity = 1000;
posXstar.resize(quantity);
posYstar.resize(quantity);
sizeStar.resize(quantity);
for (int i = 0; i < posXstar.size(); i++) {
posXstar[i] = ofRandom(-1000,1000);
posYstar[i] = ofRandom(-1000,1000);
sizeStar[i] = 0.5;
}
}
void stars::update() {
for (float i = 0; i < quantity; i++) {
if (posXstar[i] < -1) {
posXstar[i] -= 0.1;
}
else if (posXstar[i] > 1) {
posXstar[i] += 0.1;
}
else if (posXstar[i] > -1 && posXstar[i] < 1) {
posXstar[i] = 0;
}
if (posYstar[i] < -1) {
posYstar[i] -= 0.1;
}
else if (posYstar[i] > 1) {
posYstar[i] += 0.1;
}
else if (posYstar[i] > -1 && posYstar[i] < 1) {
posYstar[i] = 0;
}
sizeStar[i] = sizeStar[i] + 0.01;
if (sizeStar[i] >= 3) {
sizeStar[i] = 0.5;
posXstar[i] = ofRandom(-1000, 1000);
posYstar[i] = ofRandom(-1000, 1000);
}
}
}
void stars::draw() {
for (int i = 0; i < quantity; i++) {
ofColor(255);
ofCircle(posXstar[i], posYstar[i], sizeStar[i]);
}
}
| true |
70cf6329eaaa3994076897ce6d85a8698c979edc
|
C++
|
assceron/collaborative-real-time-editor
|
/TextEditorServer/NetworkClasses/CursorPosition.h
|
UTF-8
| 2,276 | 2.75 | 3 |
[] |
no_license
|
//
// 14/09/2019.
//
#ifndef TEXTEDITOR_CURSORPOSITION_H
#define TEXTEDITOR_CURSORPOSITION_H
#include "GenericMessage.h"
#include "../CustomCursor.h"
class CursorPosition : public GenericMessage{
public:
inline explicit CursorPosition(QJsonObject json): GenericMessage(std::move(json)){};
inline CursorPosition(const QString &docId, CustomCursor cursor, const unsigned int siteId, const QString &name):
GenericMessage(bodyTypeToQString(BodyType::cursor_position)){
insert("id", docId);
insert("cursor", cursor.toQJsonObject());
insert("site_id", QString::number(siteId));
insert("name", name);
}
inline CursorPosition(const QString &docId, CustomCursor cursor):
GenericMessage(bodyTypeToQString(BodyType::cursor_position)){
insert("id", docId);
insert("cursor", cursor.toQJsonObject());
}
inline void setSiteId(unsigned int siteId){
insert("site_id", QString::number(siteId));
}
inline void setName(const QString &name){
insert("name", name);
}
inline void setSiteColor(const QColor &color){
int r, g, b, a;
color.getRgb(&r,&g,&b,&a);
insert("site_color_r", r);
insert("site_color_g", g);
insert("site_color_b", b);
insert("site_color_a", a);
}
inline void setRemove(){
insert("remove", true);
}
[[nodiscard]] inline QColor getSiteColor() const {
int r,g,b,a;
r = _json["site_color_r"].toInt(255);
g = _json["site_color_g"].toInt(255);
b = _json["site_color_b"].toInt(255);
a = _json["site_color_a"].toInt(255);
return QColor::fromRgb(r,g,b,a);
}
[[nodiscard]] inline QString getId() const {
return _json["id"].toString();
}
[[nodiscard]] inline unsigned int getSiteId() const {
return _json["site_id"].toString().toUInt();
}
[[nodiscard]] inline QString getName() const {
return _json["name"].toString();
}
[[nodiscard]] inline CustomCursor getCursor() const {
return CustomCursor{_json["cursor"].toObject()};
}
[[nodiscard]] inline bool getRemove() const {
return _json["remove"].toBool(false);
}
};
#endif //TEXTEDITOR_CURSORPOSITION_H
| true |
d976aa5d3d2a23d6b961f622db9f25b722c7d75b
|
C++
|
CISVVC/cis201-chapter06-vectors-cmmoritz
|
/main.cpp
|
UTF-8
| 1,306 | 3.15625 | 3 |
[] |
no_license
|
/*
Description: Program will store a day, amount, and description.
It will list the daily transactions and balances. It
will calculate balances and interest.
File: main.cpp
Author: Christina Moritz
Date: 11-8-18
*/
#include<iostream>
#include "transaction.h"
#include "transactionlog.h"
void add_transactions(Transactionlog &tlog)
{
tlog.add_transaction(Transaction(1,1143.24,"Initial Balance"));
tlog.add_transaction(Transaction(2,-224,"Check 2140"));
tlog.add_transaction(Transaction(3,-193,"Check 2141"));
tlog.add_transaction(Transaction(4,500,"ATM Deposit"));
tlog.add_transaction(Transaction(5,-10,"Check 2142"));
tlog.add_transaction(Transaction(6,-105,"Check 2143"));
tlog.add_transaction(Transaction(7,-210,"Check 2144"));
tlog.add_transaction(Transaction(8,-201,"Check 2145"));
tlog.add_transaction(Transaction(16,1200,"ATM Deposit"));
tlog.add_transaction(Transaction(16,-100,"Check 2146"));
tlog.add_transaction(Transaction(17,-200,"Check 2147"));
tlog.add_transaction(Transaction(20,900,"ATM Deposit"));
tlog.add_transaction(Transaction(30,700,"ATM Deposit"));
}
int main()
{
Transactionlog tlog;
add_transactions(tlog);
tlog.print_daily_report();
return 0;
}
| true |
09941a050c6909c9e53afba8bfb8e2db7cc7c3d4
|
C++
|
ysakasin/zipper
|
/src/huffman.cpp
|
UTF-8
| 449 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
#include "huffman.h"
#include <iostream>
using namespace std;
std::pair<uint16_t, int> static_huffman_table(uint16_t x) {
if (x <= 143) {
return {0b00110000 + x, 8};
}
else if (x <= 255) {
return {0b110010000 + (x - 144), 9};
}
else if (x <= 279) {
return {0b0000000 + (x - 256), 7};
}
else if (x <= 287) {
return {0b11000000 + (x - 280), 8};
}
else {
cout << "huffman out of range" << endl;
throw "huffman out of range";
}
}
| true |
be16bf205e35f3fe75285156aff76d3d75110760
|
C++
|
legend507/Snippet
|
/Print All Path from Root to Leaf.cpp
|
UTF-8
| 1,108 | 3.765625 | 4 |
[] |
no_license
|
/*
Facebook Interview Question
Print all path from root to left -> dfs
*/
#include<vector>
#include<iostream>
using namespace std;
struct node{
char data;
node *left;
node *right;
node(char d): data(d), left(nullptr), right(nullptr){}
};
class solution_fbpath{
public:
// dfs
void printAllPath(node *root){
if(root == nullptr) return;
vector<node*> path;
helper(root, path);
}
void helper(node *root, vector<node*> &path){
// print at leaf node
if(root->left == nullptr && root->right == nullptr){
for(node *n : path)
cout << n->data << " ";
cout << root->data << " ";
cout << endl;
return;
}
path.push_back(root);
helper(root->left, path);
helper(root->right, path);
path.pop_back();
}
};
int main(){
solution_fbpath *obj = new solution_fbpath();
node *a = new node('a');
node *b = new node('b');
node *c = new node('c');
node *d = new node('d');
node *e = new node('e');
node *f = new node('f');
node *g = new node('g');
a->left = b;
a->right = c;
b->left = d;
b->right = e;
c->left = f;
c->right = g;
obj->printAllPath(a);
return 0;
}
| true |
8ea24d46f0dbbf11b386331162059c5f31518a2c
|
C++
|
naelstrof/Syme
|
/src/system/print.hpp
|
UTF-8
| 948 | 2.859375 | 3 |
[] |
no_license
|
#ifndef AS_PRINT_H_
#define AS_PRINT_H_
#include <boost/nowide/iostream.hpp>
namespace as {
template<typename T, typename... Args>
int printf( const char* s, T value, Args... args );
int printf( const char* s );
};
template<typename T, typename... Args>
int as::printf( const char* s, T value, Args... args ) {
int parses = 0;
while ( *s ) {
if ( *s == '%' ) {
if ( *( s + 1 ) == '%' ) {
s++;
} else {
boost::nowide::cout << value;
parses += 1 + as::printf( s + 1, args... ); // call even when *s == 0 to detect extra arguments
return parses;
}
}
boost::nowide::cout << *s++;
// Simulate printf's flushing on newline.
if ( *(s - 1) == '\n' ) {
boost::nowide::cout.flush();
}
}
throw std::logic_error( "extra arguments provided to printf" );
}
#endif // AS_PRINT_H_
| true |
bba5ec6227bb3214a14e54a9d456aea52984a99c
|
C++
|
opencv/opencv
|
/modules/objdetect/src/aruco/apriltag/unionfind.hpp
|
UTF-8
| 4,275 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2013-2016, The Regents of The University of Michigan.
//
// This software was developed in the APRIL Robotics Lab under the
// direction of Edwin Olson, ebolson@umich.edu. This software may be
// available under alternative licensing terms; contact the address above.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the Regents of The University of Michigan.
#ifndef _OPENCV_UNIONFIND_HPP_
#define _OPENCV_UNIONFIND_HPP_
namespace cv {
namespace aruco {
typedef struct unionfind unionfind_t;
struct unionfind{
uint32_t maxid;
struct ufrec *data;
};
struct ufrec{
// the parent of this node. If a node's parent is its own index,
// then it is a root.
uint32_t parent;
// for the root of a connected component, the number of components
// connected to it. For intermediate values, it's not meaningful.
uint32_t size;
};
static inline unionfind_t *unionfind_create(uint32_t maxid){
unionfind_t *uf = (unionfind_t*) calloc(1, sizeof(unionfind_t));
uf->maxid = maxid;
uf->data = (struct ufrec*) malloc((maxid+1) * sizeof(struct ufrec));
for (unsigned int i = 0; i <= maxid; i++) {
uf->data[i].size = 1;
uf->data[i].parent = i;
}
return uf;
}
static inline void unionfind_destroy(unionfind_t *uf){
free(uf->data);
free(uf);
}
/*
static inline uint32_t unionfind_get_representative(unionfind_t *uf, uint32_t id)
{
// base case: a node is its own parent
if (uf->data[id].parent == id)
return id;
// otherwise, recurse
uint32_t root = unionfind_get_representative(uf, uf->data[id].parent);
// short circuit the path. [XXX This write prevents tail recursion]
uf->data[id].parent = root;
return root;
}
*/
// this one seems to be every-so-slightly faster than the recursive
// version above.
static inline uint32_t unionfind_get_representative(unionfind_t *uf, uint32_t id){
uint32_t root = id;
// chase down the root
while (uf->data[root].parent != root) {
root = uf->data[root].parent;
}
// go back and collapse the tree.
//
// XXX: on some of our workloads that have very shallow trees
// (e.g. image segmentation), we are actually faster not doing
// this...
while (uf->data[id].parent != root) {
uint32_t tmp = uf->data[id].parent;
uf->data[id].parent = root;
id = tmp;
}
return root;
}
static inline uint32_t unionfind_get_set_size(unionfind_t *uf, uint32_t id){
uint32_t repid = unionfind_get_representative(uf, id);
return uf->data[repid].size;
}
static inline uint32_t unionfind_connect(unionfind_t *uf, uint32_t aid, uint32_t bid){
uint32_t aroot = unionfind_get_representative(uf, aid);
uint32_t broot = unionfind_get_representative(uf, bid);
if (aroot == broot)
return aroot;
// we don't perform "union by rank", but we perform a similar
// operation (but probably without the same asymptotic guarantee):
// We join trees based on the number of *elements* (as opposed to
// rank) contained within each tree. I.e., we use size as a proxy
// for rank. In my testing, it's often *faster* to use size than
// rank, perhaps because the rank of the tree isn't that critical
// if there are very few nodes in it.
uint32_t asize = uf->data[aroot].size;
uint32_t bsize = uf->data[broot].size;
// optimization idea: We could shortcut some or all of the tree
// that is grafted onto the other tree. Pro: those nodes were just
// read and so are probably in cache. Con: it might end up being
// wasted effort -- the tree might be grafted onto another tree in
// a moment!
if (asize > bsize) {
uf->data[broot].parent = aroot;
uf->data[aroot].size += bsize;
return aroot;
} else {
uf->data[aroot].parent = broot;
uf->data[broot].size += asize;
return broot;
}
}
}}
#endif
| true |
0c2283d9542f8f1007634d8918835d2ca76a9429
|
C++
|
tdm1223/Algorithm
|
/acmicpc.net/source/2018.cpp
|
UTF-8
| 567 | 3.625 | 4 |
[
"MIT"
] |
permissive
|
// 2018. 수들의 합 5
// 2019.08.10
// 수학
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = 0;
// n이하로 반복을 돌린다.
for (int i = 1; i <= n; i++)
{
int tmp = 0;
// i부터 n까지 연속된 수의 합을 계산해본다.
for (int j = i; j <= n; j++)
{
tmp += j;
// 동일하다면 연속된 수로 표현 가능
if (tmp == n)
{
ans++;
break;
}
// 초과한다면 더이상 볼 필요 없음
else if (tmp > n)
{
break;
}
}
}
cout << ans << endl;
return 0;
}
| true |
fdebf67d723eaa0c795c339cf75044f093d8641a
|
C++
|
green-fox-academy/Dextyh
|
/Game/game.h
|
UTF-8
| 1,987 | 2.734375 | 3 |
[] |
no_license
|
#ifndef GAME_GAME_H
#define GAME_GAME_H
#include <iostream>
#include <SDL.h>
#include <SDL_log.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include "resources.h"
//Screen dimension constants
const int SCREEN_SIZE = 600;
const int SCREEN_WIDTH = SCREEN_SIZE;
const int SCREEN_HEIGHT = SCREEN_SIZE;
//The window we'll be rendering to
SDL_Window *gWindow = nullptr;
//The window renderer
SDL_Renderer *gRenderer = nullptr;
//Starts up SDL and creates window
bool init() {
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_Log("SDL could not initialize! SDL Error: %s", SDL_GetError());
return false;
}
//Create window
gWindow = SDL_CreateWindow("Wanderer - The RPG game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == nullptr) {
SDL_Log("Window could not be created! SDL Error: %s", SDL_GetError());
return false;
}
//Create renderer for window
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
if (gRenderer == nullptr) {
SDL_Log("Renderer could not be created! SDL Error: %s", SDL_GetError());
return false;
}
//Initialize renderer color
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Initialize SDL_Image libary
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags)) {
std::cout << "Couldn't initialize SDL_Image libary";
return false;
}
//Initialize SDL_ttf libary
if (TTF_Init() == -1) {
std::cout << "Couldn't initialize SDL_ttf libary";
return false;
}
return true;
}
//Frees media and shuts down SDL
void close() {
//Destroy window
SDL_DestroyRenderer(gRenderer);
SDL_DestroyWindow(gWindow);
gWindow = nullptr;
gRenderer = nullptr;
// Quit SDL_Image
IMG_Quit();
SDL_Quit();
}
#endif
| true |
bdeb6fc6e45c015841ea40b8cd844c22c7f29804
|
C++
|
Hyukli/leetcode
|
/763.cpp
|
UTF-8
| 807 | 3.078125 | 3 |
[] |
no_license
|
#include<iostream>
#include<map>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> partitionLabels(string S) {
map<char,int> m;
for(int i=0;i<S.size();i++)
{
m[S[i]]=i;
}
vector<int> ans;
int t=m[S[0]];
for(int i=0;i<S.size();i++)
{
t=max(m[S[i]],t);
if(t==i)
{
ans.push_back(i+1);
t=0;
}
}
for(int i=ans.size()-1;i>0;i--)
{
ans[i]-=ans[i-1];
}
return ans;
}
};
int main()
{
Solution s;
string S;
cin>>S;
vector<int> ans=s.partitionLabels(S);
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
b15e7f6f60988fa1c0f3699bb406766de1b3c96f
|
C++
|
KrazyTako/space-shooter
|
/spaceShooter/main.cpp
|
UTF-8
| 8,413 | 2.546875 | 3 |
[] |
no_license
|
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <SDL_ttf.h>
#include <string>
#include <sstream>
#include "player.h"
#include "enemy.h"
#include "asteroid.h"
#include "boss.h"
using namespace std;
extern int const windowWidth = 640, windowHeight = 480;
void init(SDL_Window* gWindow, SDL_Renderer*& gRenderer)
{
SDL_Init(SDL_INIT_EVERYTHING);
gWindow = SDL_CreateWindow("Amazing Game!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_SHOWN);
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (gRenderer == NULL)
cout << "could not create renderer" << endl;
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) &imgFlags))
cout << "something stupid" << endl;
Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 2048);
TTF_Init();
}
void loadMap(SDL_Renderer* gRenderer, SDL_Texture*& map)
{
SDL_Texture* newTexture = NULL;
SDL_Surface* loadedSurface = IMG_Load("bg.png");
map = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
}
SDL_Texture* loadText(SDL_Renderer * gRenderer, SDL_Color textColor, TTF_Font* font, string text)
{
SDL_Texture* tempTexture = NULL;
SDL_Surface* textSurface = NULL;
textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if (textSurface == NULL)
{
cout << "could not load text surface" << SDL_GetError << endl;
}
tempTexture = SDL_CreateTextureFromSurface(gRenderer, textSurface);
SDL_FreeSurface(textSurface);
return tempTexture;
}
int main(int argc, char* argv[])
{
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
SDL_Event ev;
TTF_Font* gFont = NULL;
SDL_Color textColor = { 255,255,255 };
SDL_Texture* map = NULL;
SDL_Texture* playerLives = NULL;
int mapOffset = 0;
SDL_Rect colliders[10];
for (int i = 0;i < 3;i++)
{
colliders[i] = { 0,0,0,0 };
}
SDL_Rect projectiles[2];
Mix_Music* song = song=Mix_LoadMUS("leonidas.mp3");
SDL_Rect textRect = { 0,0,70,50 };
SDL_Rect levelTextRec = { (windowWidth/2)-30,(windowHeight/2)-50,70,50 };
bool level1 = true, level2 = false, level3 = false, level4 = false, victory = false;
Uint32 timer = 0;
stringstream lives,levelText;
lives.str("");
levelText.str("Level 1");
init(gWindow,gRenderer);
loadMap(gRenderer,map);
gFont = TTF_OpenFont("SIXTY.TTF", 28);
if (gFont == NULL)
{
cout << "font is NULL" << endl;
}
player player1;
player1.loadTexture(gRenderer);
enemy enemy1(gRenderer, "alien.png", 320, 0);
enemy enemy2(gRenderer, "alien.png", 460, 0, false);
enemy enemy3(gRenderer, "alien.png", 320, 0);
enemy enemy4(gRenderer, "alien.png", 460, 0, false);
enemy enemy5(gRenderer, "alien.png", 400, 0);
boss boss1(gRenderer, windowWidth / 2, 0, true);
enemy summoned(gRenderer, "alien.png", windowWidth/2, 0);
asteroid rock[10];
for (int i = 0; i < 10; i++)
{
rock[i].loadTexture(gRenderer);
}
bool quit = false;
Mix_PlayMusic(song, -1);
level4 = false;
cout << "Game test:" << endl;
cout << "move with arow keys. Hold 'a' to accelerate. spacebar to shoot" << endl;
while (!quit)
{
SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255);
SDL_RenderClear(gRenderer);
SDL_Rect mapRect = { 0,mapOffset,windowWidth,windowHeight };
SDL_Rect mapRect2 = { 0,mapOffset - 480,windowWidth,windowHeight };
SDL_RenderCopy(gRenderer, map, NULL, &mapRect);
SDL_RenderCopy(gRenderer, map, NULL, &mapRect2);
if (player1.lives > 0)
{
if (player1.fire2)
projectiles[0] = player1.getProjectile();
else
projectiles[0] = { 0,0,0,0 };
if (player1.fire4)
projectiles[1] = player1.getProjectile2();
else
projectiles[1] = { 0,0,0,0 };
while (SDL_PollEvent(&ev) == 1)
{
if (ev.type == SDL_QUIT)
{
quit = true;
}
if (!player1.hit)
{
player1.handleEvent(ev);
}
}
if (player1.a)
mapOffset = mapOffset + 4;
else
mapOffset = mapOffset + 2;
if (mapOffset > 480)
{
mapOffset = 0;
}
if (level1)
{
if (enemy1.lives == 0 && enemy2.lives == 0)
{
level1 = false;
level2 = true;
timer = SDL_GetTicks();
}
if (enemy1.lives > 0)
enemy1.render(gRenderer, projectiles);
else
enemy1.free();
if (enemy2.lives > 0)
enemy2.render(gRenderer, projectiles);
else
enemy2.free();
colliders[0] = enemy1.getCollider();
colliders[1] = enemy2.getCollider();
}
if (level2)
{
if (SDL_GetTicks() - timer < 5000)
{
levelText.str("");
levelText << "Level 2";
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()), NULL, &levelTextRec);
}
else
{
if (enemy3.lives == 0 && enemy4.lives == 0 && enemy5.lives == 0)
{
level2 = false;
level3 = true;
timer = SDL_GetTicks();
}
if (enemy3.lives > 0)
enemy3.render(gRenderer, projectiles);
else
enemy3.free();
if (enemy4.lives > 0)
enemy4.render(gRenderer, projectiles);
else
enemy4.free();
if (enemy5.lives > 0)
enemy5.render(gRenderer, projectiles);
else
enemy5.free();
colliders[0] = enemy3.getCollider();
colliders[1] = enemy4.getCollider();
colliders[2] = enemy5.getCollider();
}
}
if (level3)
{
if (SDL_GetTicks() - timer < 5000)
{
levelText.str("");
levelText << "Level 3";
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()), NULL, &levelTextRec);
}
if (SDL_GetTicks() - timer > 5000 && SDL_GetTicks() - timer < 10000)
{
SDL_Rect meteorShower = { (windowWidth / 2) - 100,(windowHeight / 2) - 20 ,250,50 };
levelText.str("");
levelText << "METEOR SHOWER DETECTED!!";
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()), NULL, &meteorShower);
}
if (SDL_GetTicks() - timer > 10000)
{
for (int i = 0;i < 10; i++)
{
rock[i].render(gRenderer);
colliders[i] = rock[i].getCollider();
}
}
if (SDL_GetTicks() - timer > 50000)
{
level4 = true;
level3 = false;
timer = SDL_GetTicks();
for (int i = 0;i < 10; i++)
{
colliders[i] = { 0,0,0,0 };
}
}
}
if (level4)
{
if (SDL_GetTicks() - timer < 5000)
{
SDL_Rect level4 = { windowWidth,windowHeight,100,50 };
levelText.str("");
levelText << "Level 4";
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()),NULL,&level4);
}
if (SDL_GetTicks() - timer > 5000)
{
if (boss1.lives > 0 || summoned.lives>0)
{
colliders[0] = boss1.getCollider();
colliders[1] = boss1.getEnemyProjectile();
boss1.render(gRenderer,projectiles);
if (boss1.summon)
{
if (summoned.lives > 0)
{
summoned.render(gRenderer, projectiles);
colliders[2] = summoned.getCollider();
}
else
{
boss1.summon = false;
summoned.lives = 5;
colliders[2] = { 0,0,0,0 };
}
}
}
else
{
colliders[0] = { 0,0,0,0 };
}
if (boss1.lives == 0)
{
level4 = false;
victory = true;
timer = SDL_GetTicks();
}
}
}
if (victory)
{
if (SDL_GetTicks() - timer < 10000)
{
levelText.str("");
levelText << "You Win! :)";
SDL_Rect winText = { (windowWidth / 2) - 50,(windowHeight / 2) + 20,50,20 };
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()), NULL, &winText);
}
}
player1.move(colliders);
player1.render(gRenderer);
SDL_RenderDrawRect(gRenderer, &player1.getProjectile2());
SDL_RenderDrawRect(gRenderer, &player1.getProjectile());
}
else
{
while (SDL_PollEvent(&ev) == 1)
{
if (ev.type == SDL_QUIT)
{
quit = true;
}
}
player1.render(gRenderer);
SDL_Rect deathText = { (windowWidth / 2)-50,windowHeight / 2,100,50 };
levelText.str("");
levelText << "Game Over!";
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, levelText.str().c_str()),NULL,&deathText);
}
lives.str("");
lives << "Lives: " << player1.lives;
SDL_RenderCopy(gRenderer, loadText(gRenderer, textColor, gFont, lives.str().c_str()), NULL, &textRect);
SDL_RenderPresent(gRenderer);
}
return 0;
}
| true |
650ba5a892e732ca10dbe5c8f267303c30fd8261
|
C++
|
HanWool-Jeong/Zigzag
|
/PlatformFuncs.cpp
|
UHC
| 2,303 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#include "PlatformFuncs.h"
#include "Arrow.h"
#include "Timers.h"
#include "ScoreBoards.h"
extern PlatformPtr platforms[13];
extern ScenePtr scene;
extern ArrowPtr arrow;
extern MakePlatformTimerPtr platformTimer;
extern SpeedupTimerPtr speedupTimer;
extern ScoreBoardPtr clickNumScore;
extern SurviveBoardPtr surviveTimeScore;
extern SpeedMeterPtr speedMeter;
void attachPlatform(PlatformPtr& elem, const PlatformPtr& prev)
{
int r;
if (prev->getX() == PLAT_CONST::MAX_LEFT_POS) { // ÷ xǥ 120 ʵ
r = DIRECTION::RIGHT;
}
else if (prev->getX() == PLAT_CONST::MAX_RIGHT_POS) { // ÷ xǥ 670 ũ ʵ
r = DIRECTION::LEFT;
}
else {
r = rand() % 2;
}
if (r == DIRECTION::LEFT) {
elem = Platform::create("images/platform.png", scene, prev->getX() + PLAT_CONST::LEFT_DX, prev->getY() + PLAT_CONST::UP_DX);
}
else {
elem = Platform::create("images/platform.png", scene, prev->getX() + PLAT_CONST::RIGHT_DX, prev->getY() + PLAT_CONST::UP_DX);
}
}
void initPlatform()
{
platforms[0] = Platform::create("images/platform.png", scene, PLAT_CONST::INIT_X, PLAT_CONST::INIT_Y);
for (int i = 1; i < sizeof(platforms) / sizeof(platforms[0]); i++) {
attachPlatform(platforms[i], platforms[i - 1]);
}
}
void movingPlatform()
{
platforms[0]->hide();
int arySize = sizeof(platforms) / sizeof(platforms[0]);
for (int i = 1; i < sizeof(platforms) / sizeof(platforms[0]); i++) {
platforms[i]->setY(platforms[i]->getY() - PLAT_CONST::UP_DX);
platforms[i]->locate(scene, platforms[i]->getX(), platforms[i]->getY());
platforms[i - 1] = platforms[i];
}
attachPlatform(platforms[arySize - 1], platforms[arySize - 2]);
}
void reInitGame()
{
for (int i = 0; i < sizeof(platforms) / sizeof(platforms[0]); i++)
platforms[i]->hide();
initPlatform();
arrow->locate(scene, ARROW_INIT::X, ARROW_INIT::Y);
arrow->setX(ARROW_INIT::X);
arrow->setY(ARROW_INIT::Y);
platformTimer->set(TIMER_CONST::INIT_SPEED);
speedupTimer->set(TIMER_CONST::INIT_SPEED_UPDATE_TIME);
speedupTimer->setIterNumZero();
clickNumScore->setScore(0);
clickNumScore->resetScoreLabel();
surviveTimeScore->setScore(0);
surviveTimeScore->resetScoreLabel();
speedMeter->resetScoreLabel();
speedMeter->setScore(1);
speedMeter->showScore();
}
| true |
54d8d21471235c3b15cf3a0c0b5686ab0a63db82
|
C++
|
ndsev/zserio
|
/compiler/extensions/cpp/runtime/src/zserio/JsonEncoder.cpp
|
UTF-8
| 2,271 | 2.9375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include <iomanip>
#include <cmath>
#include <array>
#include "zserio/JsonEncoder.h"
namespace zserio
{
void JsonEncoder::encodeNull(std::ostream& os)
{
os << "null";
}
void JsonEncoder::encodeBool(std::ostream& os, bool value)
{
os << std::boolalpha << value << std::noboolalpha;
}
void JsonEncoder::encodeFloatingPoint(std::ostream& os, double value)
{
if (std::isnan(value))
{
os << "NaN";
}
else if (std::isinf(value))
{
if (value < 0.0)
os << "-";
os << "Infinity";
}
else
{
double intPart = 1e16;
const double fractPart = std::modf(value, &intPart);
// trying to get closer to behavior of Python
if (fractPart == 0.0 && intPart > -1e16 && intPart < 1e16)
{
os << std::fixed << std::setprecision(1) << value << std::defaultfloat;
}
else
{
os << std::setprecision(15) << value << std::defaultfloat;
}
}
}
void JsonEncoder::encodeString(std::ostream& os, StringView value)
{
static const std::array<char, 17> HEX = {"0123456789abcdef"};
os.put('"');
for (char ch : value)
{
switch (ch)
{
case '\\':
case '"':
os.put('\\');
os.put(ch);
break;
case '\b':
os.put('\\');
os.put('b');
break;
case '\f':
os.put('\\');
os.put('f');
break;
case '\n':
os.put('\\');
os.put('n');
break;
case '\r':
os.put('\\');
os.put('r');
break;
case '\t':
os.put('\\');
os.put('t');
break;
default:
if (static_cast<uint8_t>(ch) <= 0x1F)
{
os.put('\\');
os.put('u');
os.put('0');
os.put('0');
os.put(HEX[static_cast<uint8_t>(static_cast<uint8_t>(ch) >> 4U) & 0xFU]);
os.put(HEX[static_cast<uint8_t>(ch) & 0xFU]);
}
else
{
os.put(ch);
}
break;
}
}
os.put('"');
}
} // namespace zserio
| true |
86046e371a6a9633658762c9f07668df2150d659
|
C++
|
Bracciata/Advent-of-Code-2020
|
/Day Four/part1.cpp
|
UTF-8
| 3,116 | 3.453125 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#include <array>
using namespace std;
// main() is where program execution begins.
int main()
{
int valid = 0;
fstream inputFile;
// Reading a file from https://www.tutorialspoint.com/read-data-from-a-text-file-using-cplusplus#:~:text=Read%20Data%20from%20a%20Text%20File%20using%20C%2B%2B,operation%20using%20object%20newfile.%204%20Example%205%20Output
inputFile.open("input.txt", ios::in); //open a file to perform read operation using file object
if (inputFile.is_open())
{ //checking whether the file is open
string tp;
std::array<bool, 7> requiredFields;
for (int i = 0; i < requiredFields.size(); i++)
{
requiredFields[i] = false;
}
while (getline(inputFile, tp))
{
//read data from file object and put it into string.
cout << tp << "\n";
if (tp.length() == 1)
{
bool isValid = true;
for (int i = 0; i < requiredFields.size(); i++)
{
if (requiredFields[i] == false)
{
isValid = false;
}
}
if (isValid)
{
valid++;
}
for (int i = 0; i < requiredFields.size(); i++)
{
requiredFields[i] = false;
}
}
else
{
if (tp.find("byr:") != std::string::npos)
{
requiredFields[0] = true;
}
if (tp.find("iyr:") != std::string::npos)
{
requiredFields[1] = true;
}
if (tp.find("eyr:") != std::string::npos)
{
requiredFields[2] = true;
}
if (tp.find("hgt:") != std::string::npos)
{
requiredFields[3] = true;
}
if (tp.find("hcl:") != std::string::npos)
{
requiredFields[4] = true;
}
if (tp.find("ecl:") != std::string::npos)
{
requiredFields[5] = true;
}
if (tp.find("pid:") != std::string::npos)
{
requiredFields[6] = true;
}
}
}
// Check one more time to ensure the final passport is covered.
bool isValid = true;
for (int i = 0; i < requiredFields.size(); i++)
{
if (requiredFields[i] == false)
{
isValid = false;
}
}
if (isValid)
{
valid++;
}
for (int i = 0; i < requiredFields.size(); i++)
{
requiredFields[i] = false;
}
inputFile.close(); //close the file object.
cout << "Total Valid: " << valid << "\n";
}
return 0;
}
| true |
468adb5cedda255ff35245a04cb2ace201eb750a
|
C++
|
cms-sw/cmssw
|
/SimTracker/TrackHistory/interface/Utils.h
|
UTF-8
| 1,416 | 2.796875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef Utils_h
#define Utils_h
#include <map>
#include <utility>
#include <vector>
//! Generic matching function
template <typename Reference, typename Association>
std::pair<typename Association::data_type::first_type, double> match(Reference key,
Association association,
bool bestMatchByMaxValue) {
typename Association::data_type::first_type value;
typename Association::const_iterator pos = association.find(key);
if (pos == association.end())
return std::pair<typename Association::data_type::first_type, double>(value, 0);
const std::vector<typename Association::data_type> &matches = pos->val;
double q = bestMatchByMaxValue ? -1e30 : 1e30;
for (std::size_t i = 0; i < matches.size(); ++i)
if (bestMatchByMaxValue ? (matches[i].second > q) : (matches[i].second < q)) {
value = matches[i].first;
q = matches[i].second;
}
return std::pair<typename Association::data_type::first_type, double>(value, q);
}
//! Class that maps the native Geant4 process types to the legacy CMS process
//! types
class G4toCMSLegacyProcTypeMap {
public:
typedef std::map<unsigned int, unsigned int> MapType;
G4toCMSLegacyProcTypeMap();
const unsigned int processId(unsigned int g4ProcessId) const;
private:
MapType m_map;
};
#endif
| true |
ebd89753438f88cd0e54b64f4d9ff56d3d76ee93
|
C++
|
aceiii/cryptopals-cpp
|
/set_3_21.cpp
|
UTF-8
| 741 | 2.90625 | 3 |
[] |
no_license
|
#include <iostream>
#include <random>
#include "mt19937.hpp"
auto main() -> int {
const uint32_t seed = 5489u;
int N = 10240;
// The 10000th consecutive invocation of a default-contructed std::mt19937 is required to produce the value 4123659995.
std::mt19937 std_mt(seed);
mt19937 mt(seed);
for (int i = 0; i < N; i += 1) {
uint32_t a = std_mt();
uint32_t b = mt.extract_number();
if (i < 10 || i == 9999 || a != b) {
std::cout << "(" << i << ") a: " << a << std::endl;
std::cout << "(" << i << ") b: " << b << std::endl;
}
if (a != b) {
std::cout << "ERROR: a != b" << std::endl;
break;
}
}
return 0;
}
| true |
fff27b6071567389322cc49e9e9a52bfc31727d6
|
C++
|
AmrARaouf/algorithm-detection
|
/graph-source-code/29-C/9367425.cpp
|
UTF-8
| 781 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
//Language: GNU C++
#include <map>
#include <cstdio>
#include <vector>
#include <iterator>
using namespace std;
map< int, vector<int> >adj;
void dfs(int node, int prev){
printf("%d ", node);
for (int i = 0; i < adj[node].size(); i++){
if (adj[node][i] == prev) continue;
dfs(adj[node][i], node);
}
}
int main(){
int n, C = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++){
int a, b;
scanf("%d%d", &a, &b);
adj[a].push_back(b);
adj[b].push_back(a);
}
for (map< int, vector<int> >::iterator it = adj.begin(); it != adj.end(); it++){
if (it->second.size() == 1){
C = it->first;
break;
}
}
dfs(C, -1);
//system("pause");
}
| true |
576fd9dd989481c13f116dfca63dc3b453e25162
|
C++
|
asdatapel/feud
|
/Client/include/AnimationDefinition.hpp
|
UTF-8
| 878 | 2.859375 | 3 |
[] |
no_license
|
#ifndef FEUD_ANIMATIONDEFINITION_HPP
#define FEUD_ANIMATIONDEFINITION_HPP
#include <functional>
#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
struct AnimationDefinition
{
unsigned int entityId;
glm::vec3 startPosition;
glm::quat startRotation;
glm::vec3 endPosition;
glm::quat endRotation;
float length;
std::function<float(float)> interpolation = Linear; // should take a value 0.f-1.f and return 0.f-1.f
static float Linear(float t) { return t; };
static float Exponential(float t) { return t * t; };
static float EaseOutElastic(float t)
{
const float c4 = (2 * 3.1415) / 3;
return t == 0.f ? 0 : t == 1 ? 1 : pow(2, -10 * t) * sin((t * 10 - 0.75f) * c4) + 1;
};
static float EaseOutCubic(float t)
{
return 1 - std::pow(1 - t, 3);
}
};
#endif //FEUD_ANIMATIONDEFINITION_HPP
| true |
fe981040fe3a43b6649e4e5aa34742652b8f4abe
|
C++
|
CDDDJ-A-2015/Project
|
/EditProject.cpp
|
UTF-8
| 5,518 | 2.546875 | 3 |
[] |
no_license
|
/*
* File: EditProject.cpp
* Author: dm940
*
* Created on 14 May 2015, 6:01 PM
*/
#include "EditProject.h"
#include "Project.h"
#include "Coco1.h"
#include "Coco2.h"
#include "FuncPoints.h"
#include <QMessageBox>
#include "TeamMembers.h"
using namespace std;
EditProject::EditProject() {
widget.setupUi(this);
connect(widget.buttonBox,SIGNAL(accepted()),this,SLOT(clickSave()));
connect(widget.buttonBox,SIGNAL(rejected()),this,SLOT(clickCancel()));
connect(widget.bChooseManager,SIGNAL(clicked()),this,SLOT(clickbChooseManager()));
connect(widget.bC1,SIGNAL(clicked()),this,SLOT(clickbC1()));
connect(widget.bC2,SIGNAL(clicked()),this,SLOT(clickbC2()));
connect(widget.bFP,SIGNAL(clicked()),this,SLOT(clickbFP()));
id = -1;
save = false;
widget.dBeg->setDate(QDateTime::currentDateTime().date());
P.Manager_ID = -1;
}
EditProject::~EditProject() {
}
void EditProject::clickSave() {
//ensure everything is correct
if(P.Manager_ID == -1) {
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("You cannot make a new Project without a manager");
msgBox.exec();
return;
}
close();
save = true;
if(id == -1) { //New project
strcpy(P.Name,widget.eProjName->text().toStdString().c_str());
strcpy(P.Beg_Date,widget.dBeg->text().toStdString().c_str());
strcpy(P.Description,widget.eDesc->toPlainText().toStdString().c_str());
P.CCMO1 = widget.lC1->text().toInt();
P.CCMO2 = widget.lC2->text().toInt();
P.F_Points = widget.lFP->text().toInt();
strcpy(P.End_Date,widget.dBeg->text().toStdString().c_str());
strcpy(P.Last_Updated,"aa");;
createProject();
widget.lID->setText(QString::number(id));
//add Project and get id =
}
else {
//save project
}
Project *vProject = new Project;
vProject->setID(widget.lID->text().toInt());
vProject->show();
}
void EditProject::clickCancel() {
close();
if (id != -1) {
Project *vProject = new Project;
vProject->setID(id);
vProject->show();
}
}
void EditProject::setID(int tmp) {
id = tmp;
widget.lID->setText(QString::number(id));
getProject();
widget.eProjName->setReadOnly(true);
widget.bChooseManager->hide();
}
void EditProject::clickbC1() {
Coco1 vC1;
vC1.exec();
if (vC1.result() == QDialog::Accepted) {
widget.lC1->setText(QString::number(vC1.calc()));
}
}
void EditProject::clickbC2() {
Coco2 vC2;
vC2.exec();
if (vC2.result() == QDialog::Accepted) {
widget.lC2->setText(QString::number(vC2.calc()));
}
}
void EditProject::clickbFP() {
FuncPoints vFP;
vFP.exec();
if (vFP.result() == QDialog::Accepted) {
widget.lFP->setText(QString::number(vFP.calc()));
}
}
void EditProject::clickbChooseManager() {
TeamMembers *vTeamMembers = new TeamMembers;
vTeamMembers->setID(2,0);
vTeamMembers->exec();
if (vTeamMembers->result() == QDialog::Accepted) {
P.Manager_ID = vTeamMembers->getGID();
widget.lManager->setText("Manager: " + vTeamMembers->getGName());
}
}
void EditProject::createProject()
{
Type_Packet T;
Request_Packet RP;
int n;
RP.Request = false;
//Send to server that client is about to request something
n = write(sockfd,&RP,sizeof(RP));
if (n < 0)
cout << "ERROR writing to socket" << endl;
T.T = 2;
//Send to server that client is about to send a login packet
int PID = -1;
T.ID = PID;
n = write(sockfd,&T,sizeof(T));
if (n < 0)
cout << "ERROR writing to socket" << endl;
/*
FILL THIS PACKET FOR ME DAVID
ITS IN CLIENT_SIDE.h
*/
//createProject_Packet P; // <<<<<<
n = write(sockfd, &P, sizeof(P));
if(n < 0)
cout << "Error writing to socket" << endl;
n = read(sockfd, &id, sizeof(int));
if(n < 0)
cout <<"error reading from socket" << endl;
}
void EditProject::getProject()
{
Type_Packet T;
Request_Packet RP;
int n;
RP.Request = true;
//Send to server that client is about to request something
n = write(sockfd,&RP,sizeof(RP));
if (n < 0)
cout << "ERROR writing to socket" << endl;
//Send to server that client is about to send The Global Project List
T.T = 21;
T.ID = id;
n = write(sockfd,&T,sizeof(T));
if (n < 0)
cout << "ERROR writing to socket" << endl;
n = read(sockfd,&T,sizeof(T));
if (n < 0)
cout << "ERROR reading to socket" << endl;
if(T.T == 21)
{
bool exit = false;
do{
Project_Packet PP;
//Receive Project List Packets
n = read(sockfd,&PP,sizeof(PP));
if (n < 0)
cout << "ERROR reading to socket" << endl;
if(PP.Manager_ID == -1)
{
exit = true;
break;
}
widget.eProjName->setText(PP.Name);
widget.eDesc->clear();
widget.eDesc->insertPlainText(PP.Description);
widget.dBeg->setDate(QDate::fromString(PP.End_Date,"dd/MM/yyyy"));
//P.Progress = PP.Progress;
//strcpy(P.End_Date, PP.End_Date);
widget.lManager->setText(PP.Manager_Name);
P.Manager_ID = PP.Manager_ID;
widget.lC1->setText(QString::number(PP.CCMO1) + "p/m");
widget.lC2->setText(QString::number(PP.CCMO2) + "p/m");
widget.lFP->setText(QString::number(PP.F_Points));
}while(exit == false);
}
else
cout << "ERROR, different type of packet received! Packet was: " << T.T << "." << endl;
}
| true |
8e6150ec418abe92a7ed64deb8cca0e1e0c1d55a
|
C++
|
ZFDxiaoer/algorithm
|
/quicksort.cpp
|
UTF-8
| 1,454 | 2.859375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <map>
#include <limits>
#include <climits>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <math.h>
#include <sstream>
#include <deque>
#include <ctime>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
};
int PartPation(int A[],int low,int high){
int pivot = A[low];
while(low<high){
while(low<high && A[high]>=pivot) high--;
A[low] = A[high];
while(low<high && A[low]<=pivot) low++;
A[high] = A[low];
}
A[low] = pivot;
return low;
}
void QuickSort(int A[],int low, int high){
if(low<high){
int pivotpos = PartPation(A,low,high);
QuickSort(A,low,pivotpos-1);
QuickSort(A,pivotpos+1,high);
}
}
int main()
{
int a[] = {25,84,21,47,15,27,68,35,20};
int len = 9;
QuickSort(a,0,8);
for(int i=0;i<len;i++)
cout << a[i] << " ";
cout << endl;
//
// int b[] = {25,84,21,47,15,27,68,35,20};
// MergeSort(b,0,8);
// for(int i=0;i<len;i++)
// cout << b[i] << " ";
// cout << endl;
// int c[] = {0,25,84,21,47,15,27,68,35,20};
// int le = 9;
// HeapSort(c,le);
// for(int i=1;i<=le;i++)
// cout << c[i] << " ";
return 0;
}
| true |
142714628ad68f069e62b82416ef9dcf9a44d42d
|
C++
|
gargVader/CPP-Data-Structures-Algorithms-Launchpad
|
/Binary Tree/11. Nodes at distance K from from given target node.cpp
|
UTF-8
| 2,339 | 3.90625 | 4 |
[] |
no_license
|
#include<iostream>
#include<queue>
using namespace std;
class node {
public:
int data;
node *right = NULL;
node*left = NULL;
node(int d) {
data = d;
}
};
node* buildTree() {
int d; cin >> d;
// Base Case
if (d == -1) {
return NULL;
}
node *root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
// bfs with newline character
void bfs(node *root) {
if (root == NULL) {
return;
}
queue<node*> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node *f = q.front();
if (f == NULL) {
cout << endl;
q.pop();
// If after popping NULL, queue is empty that means it has no more children and we have reached the end or leaf node
if (!q.empty()) {
q.push(NULL);
}
} else {
cout << f->data << " ";
q.pop();
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
}
}
void printKthLevel(node *root, int k) {
if (root == NULL) {
return;
}
if (k == 0) {
cout << root->data << " ";
return;
}
printKthLevel(root->left, k - 1);
printKthLevel(root->right, k - 1);
}
int printAtDistanceK(node *root, node *target, int k) {
// Base Case
if (root == NULL) {
return -1;
}
if (root == target) {
printKthLevel(root, k);
return 0;
}
// we are now at some ancestor
// call on left subtree of ancestor
// distance of left-subtree root from the target node . It will give DL=0
int DL = printAtDistanceK(root->left, target, k);
if (DL != -1) {
// Target node is present in left subtree
// Two cases: 1. print the ancestor node itself(K-2-DL==-1) 2. Otherwise call on right
if (k - 2 - DL == -1) {
cout << root->data << " ";
} else {
printKthLevel(root->right, k - 2 - DL);
}
return DL + 1;
}
int DR = printAtDistanceK(root->right, target, k);
if (DR != -1) {
// Target node is present in right subtree
// Two cases: 1. print the ancestor node itself(K-2-DR==-1) 2. Otherwise call on right
if (k - 2 - DR == -1) {
cout << root->data << " ";
} else {
printKthLevel(root->left, k - 2 - DR);
}
return DR + 1;
}
// node was not present in the left or right part
return -1;
}
int main() {
node *root = buildTree();
printAtDistanceK(root, root->left->left, 3);
}
// 1 2 4 6 -1 -1 7 10 -1 -1 11 -1 -1 5 8 -1 -1 9 -1 -1 3 -1 -1
| true |
8b5613ff34b775d7d8c83d021d105e0191937607
|
C++
|
warzes/Soulvania
|
/code/SoulVania/WhipFlashingRenderingSystem.cpp
|
UTF-8
| 3,243 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#include "stdafx.h"
#include "WhipFlashingRenderingSystem.h"
#include "MathHelper.h"
#include "Whip.h"
#include "Settings.h"
WhipFlashingRenderingSystem::WhipFlashingRenderingSystem(Whip &parent, std::string spriteConfigPath) :
WhipRenderingSystem{ parent, spriteConfigPath }
{
}
void WhipFlashingRenderingSystem::Receive(int message)
{
WhipRenderingSystem::Receive(message);
switch (message)
{
case FACING_CHANGED:
OnFacingChanged();
break;
}
}
void WhipFlashingRenderingSystem::LoadContent(ContentManager &content)
{
RenderingSystem::LoadContent(content);
auto animationFactory = content.Load<AnimationFactory>(spriteConfigPath);
auto animations_mangenta = std::vector<std::string>{ "Whip_level_03_magenta" };
auto animations_red = std::vector<std::string>{ "Whip_level_03_red" };
auto animations_yellow = std::vector<std::string>{ "Whip_level_03_yellow" };
auto animations_blue = std::vector<std::string>{ "Whip_level_03_blue" };
sprite = std::make_unique<AnimatedSprite>(animationFactory, animations_mangenta);
spriteRed = std::make_unique<AnimatedSprite>(animationFactory, animations_red);
spriteYellow = std::make_unique<AnimatedSprite>(animationFactory, animations_yellow);
spriteBlue = std::make_unique<AnimatedSprite>(animationFactory, animations_blue);
}
void WhipFlashingRenderingSystem::Update(GameTime gameTime)
{
if (!sprite->IsVisible())
return;
if (sprite->GetCurrentAnimation().GetCurrentFrameIndex() == 2)
parent.GetBody().Enabled(true);
sprite->Update();
spriteRed->Update();
spriteYellow->Update();
spriteBlue->Update();
UpdatePositionRelativeToPlayer();
currentColor = MathHelper::RandomBetween(1, 4, currentColor);
}
void WhipFlashingRenderingSystem::Draw(SpriteExtensions &spriteBatch)
{
if (!sprite->IsVisible())
return;
RenderingSystem::Draw(spriteBatch);
switch (currentColor)
{
case 1:
spriteBatch.Draw(*sprite, parent.GetPosition());
break;
case 2:
spriteBatch.Draw(*spriteRed, parent.GetPosition());
break;
case 3:
spriteBatch.Draw(*spriteYellow, parent.GetPosition());
break;
case 4:
spriteBatch.Draw(*spriteBlue, parent.GetPosition());
break;
}
}
void WhipFlashingRenderingSystem::OnWhipUnleashed()
{
UpdatePositionRelativeToPlayer();
sprite->Play("Whip_level_03_magenta");
spriteRed->Play("Whip_level_03_red");
spriteYellow->Play("Whip_level_03_yellow");
spriteBlue->Play("Whip_level_03_blue");
sprite->SetVisibility(true);
}
void WhipFlashingRenderingSystem::OnWhipWithdrawn()
{
sprite->GetCurrentAnimation().Reset();
spriteRed->GetCurrentAnimation().Reset();
spriteYellow->GetCurrentAnimation().Reset();
spriteBlue->GetCurrentAnimation().Reset();
sprite->SetVisibility(false);
}
void WhipFlashingRenderingSystem::OnFacingChanged()
{
if (parent.GetFacing() == Facing::Left)
{
sprite->SetEffect(SpriteEffects::FlipHorizontally);
spriteRed->SetEffect(SpriteEffects::FlipHorizontally);
spriteYellow->SetEffect(SpriteEffects::FlipHorizontally);
spriteBlue->SetEffect(SpriteEffects::FlipHorizontally);
}
else
{
sprite->SetEffect(SpriteEffects::None);
spriteRed->SetEffect(SpriteEffects::None);
spriteYellow->SetEffect(SpriteEffects::None);
spriteBlue->SetEffect(SpriteEffects::None);
}
}
| true |
cc5caf1fdcf86fe152140b45da8473f639bcf4c7
|
C++
|
ennis/stronghold
|
/code/src/shape/Polygon2D.cpp
|
UTF-8
| 1,342 | 3.125 | 3 |
[] |
no_license
|
#include "Polygon2D.hpp"
#include <sstream>
Polygon2D::Polygon2D() : Shape(ST_Polygon, glm::vec3(), glm::quat())
{}
void Polygon2D::addPoint(glm::vec2 const &point)
{
points.push_back(point);
}
std::string Polygon2D::toString() const
{
std::ostringstream ss;
std::vector<glm::vec2>::const_iterator it = points.begin();
while (it != points.end()) {
ss << "(" << it->x << "," << it->y << ") ";
it++;
}
return ss.str();
}
bool Polygon2D::inside_polygon (glm::vec2 pt) const {
int i, j;
bool c = false;
int npol = points.size();
for (i = 0, j = npol-1; i < npol; j = i++) {
if ((((points[i].y<=pt.y) && (pt.y<points[j].y)) ||
((points[j].y<=pt.y) && (pt.y<points[i].y))) &&
(pt.x < (points[j].x - points[i].x) * (pt.y - points[i].y) / (points[j].y - points[i].y) + points[i].x))
c = !c;
}
return c;
}
void Polygon2D::getBounds(glm::vec2 &a, glm::vec2 &b) const
{
float minx = 0.f, maxx = 0.f;
float miny = 0.f, maxy = 0.f;
for (std::vector<glm::vec2>::const_iterator it = points.begin(); it != points.end(); ++it) {
glm::vec2 v = *it;
if (v.x > maxx) {
maxx = v.x;
}
if (v.x < minx) {
minx = v.x;
}
if (v.y > maxy) {
maxy = v.y;
}
if (v.y < miny) {
miny = v.y;
}
}
a = glm::vec2(minx, miny);
b = glm::vec2(maxx, maxy);
}
| true |
7b5c71343226b2db7fd392cb09bf7179a71ba0f2
|
C++
|
Primus023008/LeetcodeSolutions_cpp
|
/Maths/Easy/ExcelSheetColumnTitle.cpp
|
UTF-8
| 732 | 3.359375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
char toChar(int n)
{
if (n == 0)
return 'Z';
return char(64 + n);
}
string convertToTitle(int columnNumber)
{
string str = "";
while (columnNumber > 0)
{
char c = toChar(columnNumber % 26);
if (columnNumber % 26 == 0)
{
columnNumber = (columnNumber / 26) - 1;
}
else
{
columnNumber /= 26;
}
str = c + str;
}
return str;
}
};
int main()
{
Solution s;
int columnNumber= 2147483647;
cout<<s.convertToTitle(columnNumber);
}
| true |
4eea624b1c96a6949c469a6792573eae75d6cecd
|
C++
|
ajay09/design_patterns
|
/behavioral/1_strategyPattern/3_dynamic_array_7.cpp
|
UTF-8
| 6,781 | 3.75 | 4 |
[] |
no_license
|
/*
A thread-safe Array class using Strategy Pattern.
Applying Strategy Pattern
Our previous approach led to a lot of conditional statements.
In this case the different algo are locking and not-locking.
Thus we take these algo out and encapsulate them in their own
classes.
- Create a base-class that will define the interface of locking and unlocking (for any object)
- Create sub-classes that will decide what kind of mutex to use for locks.
Problem with current :
- What if the use passes nullptr while creating instance of Array?
(i.e. the client may not specify a strategy.)
- How do we indicate that we wish to use Array in Single-threaded app?
Although adding
if (arr.m_pLockPolicy)
solved the previous problem, but now our code looks similar to that in 3_dynamic_array_5.cpp
Thus we need a better approach to solve this issue.
*/
#include <vector>
#include <iostream>
#include <mutex>
namespace V1
{
template <typename T>
class Array {
std::vector<T> m_Vector;
mutable std::mutex m_Mtx;
public:
void Add(const T& element) {
std::lock_guard<std::mutex> lock{m_Mtx};
m_Vector.push_back(element);
}
void Insert(size_t index, const T& element) {
std::lock_guard<std::mutex> lock{m_Mtx};
m_Vector.insert(begin(m_Vector) + index, element);
}
void Erase(size_t index) {
std::lock_guard<std::mutex> lock{m_Mtx};
m_Vector.erase(begin(m_Vector) + index);
}
// The next 2 methods need not be thread-safe because
// they are not modifying the state of the Array object.
T& operator[](size_t index) {
return m_Vector[index];
}
const T& operator[](size_t index) const {
return m_Vector[index];
}
size_t Size() const {
std::lock_guard<std::mutex> lock{m_Mtx};
return m_Vector.size();
}
template <typename K>
friend std::ostream& operator<<(std::ostream& os, const Array<K>& arr);
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Array<T>& arr) {
std::lock_guard<std::mutex> lock{arr.m_Mtx};
for (auto element : arr.m_Vector) {
os << element << ", ";
}
return os << "\n";
}
};
namespace V2
{
template <typename T>
class Array {
std::vector<T> m_Vector;
mutable std::mutex m_Mtx;
bool m_IsMultithreaded; // to decide whether to apply locks or not.
// I true we will apply the locks otherwise not.
// This will be specified by the clients through the constructor.
public:
Array(bool threading=false) : m_IsMultithreaded{threading} {
}
void Add(const T& element) {
if (m_IsMultithreaded)
m_Mtx.lock();
m_Vector.push_back(element);
if (m_IsMultithreaded)
m_Mtx.unlock();
}
void Insert(size_t index, const T& element) {
if (m_IsMultithreaded)
m_Mtx.lock();
m_Vector.insert(begin(m_Vector) + index, element);
if (m_IsMultithreaded)
m_Mtx.unlock();
}
void Erase(size_t index) {
if (m_IsMultithreaded)
m_Mtx.lock();
m_Vector.erase(begin(m_Vector) + index);
if (m_IsMultithreaded)
m_Mtx.unlock();
}
// The next 2 methods need not be thread-safe because
// they are not modifying the state of the Array object.
T& operator[](size_t index) {
return m_Vector[index];
}
const T& operator[](size_t index) const {
return m_Vector[index];
}
size_t Size() const {
if (m_IsMultithreaded)
m_Mtx.lock();
size_t size = m_Vector.size();
if (m_IsMultithreaded)
m_Mtx.unlock();
return size;
}
template <typename K>
friend std::ostream& operator<<(std::ostream& os, const Array<K>& arr);
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Array<T>& arr) {
if (arr.m_IsMultithreaded)
arr.m_Mtx.lock();
for (auto element : arr.m_Vector) {
os << element << ", ";
}
if (arr.m_IsMultithreaded)
arr.m_Mtx.unlock();
return os << "\n";
}
};
///////////////////////////////////////////
///////////////////// LockPolicy.h
///////////////////////////////////////////
class LockPolicy {
public:
virtual void lock() = 0;
virtual void unlock() = 0;
virtual ~LockPolicy() = default;
};
///////////////////////////////////////////
///////////////////// MutexLock.h
///////////////////////////////////////////
class MutexLock : public LockPolicy {
std::mutex m_Mtx;
public:
virtual void lock() override {
m_Mtx.lock();
}
virtual void unlock() override {
m_Mtx.unlock();
}
};
template <typename T>
class Array {
std::vector<T> m_Vector;
LockPolicy *m_pLockPolicy; // m_pLockPolicy is a dependecy for Array class
// and we have to inject this dependency.
public:
Array(LockPolicy *policy) : m_pLockPolicy{policy} {
}
/*
We didn't use the setter method to set the Lock Policy because once the policy is set
we need not change it for that object.
Thus we inject the dependency using the constructor.
*/
void Add(const T& element) {
if (m_pLockPolicy) // adding the if statement solve both the issues senn in the previous implementation.
m_pLockPolicy->lock();
m_Vector.push_back(element);
if (m_pLockPolicy)
m_pLockPolicy->unlock();
}
void Insert(size_t index, const T& element) {
if (m_pLockPolicy)
m_pLockPolicy->lock();
m_Vector.insert(begin(m_Vector) + index, element);
if (m_pLockPolicy)
m_pLockPolicy->unlock();
}
void Erase(size_t index) {
if (m_pLockPolicy)
m_pLockPolicy->lock();
m_Vector.erase(begin(m_Vector) + index);
if (m_pLockPolicy)
m_pLockPolicy->unlock();
}
// The next 2 methods need not be thread-safe because
// they are not modifying the state of the Array object.
T& operator[](size_t index) {
return m_Vector[index];
}
const T& operator[](size_t index) const {
return m_Vector[index];
}
size_t Size() const {
if (m_pLockPolicy)
m_pLockPolicy->lock();
size_t size = m_Vector.size();
if (m_pLockPolicy)
m_pLockPolicy->unlock();
return size;
}
template <typename K>
friend std::ostream& operator<<(std::ostream& os, const Array<K>& arr);
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Array<T>& arr) {
if (arr.m_pLockPolicy)
arr.m_pLockPolicy->lock();
for (auto element : arr.m_Vector) {
os << element << ", ";
}
if (arr.m_pLockPolicy)
arr.m_pLockPolicy->unlock();
return os << "\n";
}
#include <thread>
void Operate(Array<int> &data) {
data[0] = 100;
for (int i = 0; i < 50; ++i) {
data.Insert(i, i * 55);
}
}
int main() {
Array<int> data{new MutexLock{}};
for (int i = 0; i < 100; ++i)
data.Add(i);
std::thread t{Operate, std::ref(data)};
// To enable thread Operate() to acquire lock befor the main thread.
using namespace std::chrono_literals;
std::this_thread::sleep_for(500ms);
std::cout << data;
t.join();
return 0;
}
| true |
8357337f8abb9626270e9ae7e6c38ca6b7a2b16f
|
C++
|
dominik3131/PO
|
/PO/complex/wyk3/07-vector/testvector.cpp
|
UTF-8
| 239 | 2.84375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
#include "vector.h"
void
printvector (vector v)
{
cout << v << endl;
}
int
main ()
{
vector a (10);
cout << a << endl;
a[0] = 15;
a[5] = 32;
vector b(10);
b=a;
printvector (b);
}
| true |
c6d69e8182a181319a80c35b2bcfe824909da75b
|
C++
|
Totomosic/Ablaze2
|
/Ablaze/src/Scene/Scene.h
|
UTF-8
| 1,500 | 2.625 | 3 |
[] |
no_license
|
#pragma once
#include "Common.h"
#include "Layer.h"
namespace Ablaze
{
struct LayerMask;
// Object that stores and manages all relavent Entities and Cameras
class AB_API Scene : public Object
{
private:
std::unordered_map<String, Layer*> m_Layers;
std::vector<Layer*> m_LayerOrder;
Layer* m_CurrentLayer;
private:
Scene();
Scene(const String& layerName, GameObject* layerCamera = nullptr);
~Scene();
public:
bool HasLayer() const;
bool HasLayer(const String& layerName) const;
const Layer& CurrentLayer() const;
Layer& CurrentLayer();
const Layer& GetLayer(const String& layer) const;
Layer& GetLayer(const String& layer);
const Layer& GetLayer(int index) const;
Layer& GetLayer(int index);
const std::vector<Layer*>& GetLayers() const;
std::vector<Layer*> GetLayers(int layerMask) const;
std::vector<Layer*> GetLayers(const LayerMask& layerMask) const;
int GetMask(Layer* layer) const;
int GetMask(const String& layerName) const;
Layer& CreateLayer(const String& name, GameObject* camera = nullptr);
Layer& CreateLayer(GameObject* camera = nullptr); // Assigned random name
Layer& SetCurrentLayer(const String& name);
Layer& SetCurrentLayer(Layer* layer);
Layer& SetCurrentLayer(int index);
void AddLayer(Layer* layer);
const Layer& operator[](const String& layer) const;
Layer& operator[](const String& layer);
String ToString() const override;
void Serialize(JSONwriter& writer) const;
friend class SceneManager;
};
}
| true |
9353a1acc5aad47c94576c0238fdb4df9c2d6626
|
C++
|
yyzYLMF/myleetcode
|
/54_spiral_matrix.cc
|
UTF-8
| 2,309 | 3.78125 | 4 |
[] |
no_license
|
/*
@yang 2015/3/13
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
*/
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
int m,n,count,direct,i,j;
vector<int> result;
int **sign;
if(matrix.size() == 0)
return result;
m = matrix.size();
n = matrix[0].size();
if(m*n == 0)
return result;
sign = new int*[m];
for(i=0; i<m; ++i)
sign[i] = new int[n];
for(i=0; i<m; ++i) {
for(j=0; j<n; ++j) {
sign[i][j] = 0;
}
}
i=0;
j=0;
direct=0;
count=0;
while(count != m*n) {
result.push_back(matrix[i][j]);
sign[i][j] = 1;
count++;
if(direct == 0) {
j++;
if(j>=n || sign[i][j] == 1) {
direct=1;
j--;
i++;
}
}
else if(direct == 1) {
i++;
if(i>=m || sign[i][j] == 1) {
direct=2;
i--;
j--;
}
}
else if(direct == 2) {
j--;
if(j<0 || sign[i][j] == 1) {
direct=3;
j++;
i--;
}
}
else {
i--;
if(i<0 || sign[i][j] == 1) {
direct=0;
i++;
j++;
}
}
}
return result;
}
};
int main() {
vector<int> input1(3,1);
vector<int> input2(3,2);
vector<vector<int> > input;
vector<int> result;
Solution solu;
input.push_back(input1);
input.push_back(input2);
result = solu.spiralOrder(input);
for(int i=0; i<result.size(); ++i) {
cout<<result[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
2bf3c178f30c0b341ea8aa1a168b5b968be76fe7
|
C++
|
Bona612/GOP
|
/src/Game/Game.cpp
|
WINDOWS-1252
| 8,191 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstring>
#include <iomanip>
#include "Game.h"
#include "../Dice/Dice.h"
#include "../Box/VoidBox.h"
#include "../Box/DrawCardBox.h"
#include "../Box/MoveBox.h"
#include "../Box/MissTurnBox.h"
#include "../Box/BackStartBox.h"
#include "../Box/StartBox.h"
#include "../Box/FinishBox.h"
#include "../Utils/Utils.h"
#include "../Card/Card.h"
#include "../Color/Color.h"
using namespace std;
#define N_COLUMNS 3
#define W_COLUMN 50
Game::Game()
{
srand(time(NULL));
startOutput();
//inizializzazione di tutti i componenti del gioco
createPlayers();
createBillboard();
deck = new Deck();
dice = new Dice();
}
//metodo che esegue il gioco fino a che non finisce
void Game::startGame()
{
while (!isFinish)
{
playerTurn();
}
endGame();
}
void Game::startOutput()
{
cout << endl << "GOP - Gioco dell'oca - Tema Calcio" << endl;
cout << "- Premi invio per confermare e proseguire!" << endl << endl;
}
//crea i giocatori
void Game::createPlayers()
{
char name[50];
char color[10];
while (numPlayers < 2 || numPlayers > 6)
{
cout << "Numero di giocatori (da 2 a 6): ";
cin >> numPlayers;
cout << endl;
if (numPlayers < 2 || numPlayers > 6)
{
cout << "Valore errato! ";
clearCin();
}
}
for(int i = 0; i < numPlayers; ++i)
{
cout << "Nome giocatore " << i+1 << ": ";
cin >> name;
color[0] = ' ' ;
while(getCharColor(color) == -1)
{
cout << "Colore giocatore " << i+1 << ": ";
cin >> color;
cout << endl;
if (getCharColor(color) == -1)
{
cout << "Colore non presente! ";
clearCin();
}
}
players[i] = new Player(name, getCharColor(color));
}
// Reset dello stream di input
cin.get();
}
//creazione del tabellone
void Game::createBillboard()
{
this->numBoxes = rand() % 61 + 40;
boxes[0] = new StartBox();
boxes[numBoxes - 1] = new FinishBox();
int randInt = 0;
for (int i = 1; i < numBoxes - 1; i++)
{
randInt = rand() % 100;
if (randInt < 15)
{
boxes[i] = new VoidBox();
}
else if(randInt < 40)
{
boxes[i] = new DrawCardBox();
}
else if(randInt < 60)
{
boxes[i] = new MoveBox(rand() % 5 + 1);
}
else if(randInt < 80)
{
boxes[i] = new MoveBox(-(rand() % 5 + 1));
}
else if(randInt < 95)
{
boxes[i] = new MissTurnBox(1);
}
else
{
boxes[i] = new BackStartBox();
}
}
}
//turno di uno dei giocatori
void Game::playerTurn()
{
cout << endl;
separate();
showBillboard();
cout << endl;
cout << "Turno di " << players[currPlayer]->getName()
<< " - Giocatore " << currPlayer + 1
<< " - Casella corrente: " << players[currPlayer]->getPos() << endl;
pause();
if (players[currPlayer]->isBlocked())
{
cout << getRed() << "Salta il turno" << getReset() << endl;
pause();
}
else
{
throwDice();
}
currPlayer = nextPlayer();
}
//metodo che richiama il lancio del dado
void Game::throwDice()
{
int score = dice->throwDice();
cout << "Hai fatto " << score << endl;
movePlayer(score);
}
//metodo che esegue l'operazione della casella su cui arrivato il giocatore
void Game::executeBox()
{
boxes[players[currPlayer]->getPos()]->effect(this);
}
//restituisce il giocatore successivo
int Game::nextPlayer()
{
if (currPlayer == numPlayers - 1)
{
return 0;
}
return currPlayer + 1;
}
//restituisce il giocatore precedente
int Game::prevPlayer()
{
if (currPlayer == 0)
{
return numPlayers - 1;
}
return currPlayer - 1;
}
//esegue lo spostamento del giocatore ed applica l'effeto della nuova casella
void Game::movePlayer(int movement)
{
char s[50];
int newPos = players[currPlayer]->getPos() + movement;
if (newPos >= numBoxes)
{
newPos = (numBoxes - 1) - (newPos - (numBoxes - 1));
}
if (newPos < 0)
{
newPos = 0;
}
players[currPlayer]->setPos(newPos);
add_color(s, boxes[players[currPlayer]->getPos()]->getText(), boxes[players[currPlayer]->getPos()]->getColor());
cout << endl << "Casella " << players[currPlayer]->getPos() << ": " << s;
pause();
executeBox();
}
//pesca una carta dal mazzo
void Game::drawCard()
{
executeCard(deck->drawCard());
}
//manda a video il testo della carta ed esegue l'operazione della carta
void Game::executeCard(Card* card)
{
cout << endl << "Carta: " << card->getText();
pause();
card->effetto(this);
}
//salta turno/i
void Game::missTurn(int turns)
{
players[currPlayer]->setNumTurns(turns);
}
//torna alla partenza
void Game::backStart()
{
players[currPlayer]->setPos(0);
}
//tira ancora
void Game::throwAgain()
{
throwDice();
}
//cambia la posizione del giocatore attuale con uno tra quello precedente o quello successivo
void Game::switchPosition(int p)
{
char s[50];
if (numPlayers < 2)
{
return;
}
int posPlayer = players[currPlayer]->getPos();
int posPlayer2 = players[(p == 1 ? nextPlayer() : prevPlayer())]->getPos();
players[currPlayer]->setPos(posPlayer2);
players[nextPlayer()]->setPos(posPlayer);
add_color(s, boxes[players[currPlayer]->getPos()]->getText(), boxes[players[currPlayer]->getPos()]->getColor());
cout << endl << "Sei finito nella casella " << players[currPlayer]->getPos() << ": " << s << endl;
executeBox();
}
//casella arrivo
void Game::finish()
{
isFinish = true;
}
//metodo che mostra dove i giocatori si trovano al momento mandando in output un asterisco colorato
void Game::show_players_position(char* c, const int pos)
{
for (int i = 0; i < numPlayers; i++)
{
if (players[i]->getPos() == pos)
{
if (c[0] == '\0')
{
add_color(c, (char *)("*"), players[i]->getColorPlayer());
}
else
{
add_const_color(c, (char *)("*"), players[i]->getColorPlayer());
}
}
else if (c[0] == '\0')
{
add_color(c, (char *)(" "), players[i]->getColorPlayer());
}
else
{
add_const_color(c, (char *)(" "), players[i]->getColorPlayer());
}
(i == (numPlayers - 1)) ? strcat(c, (char *)(" ")) : strcat(c, (char *)(""));
}
}
//metodo che restituisce in output il tabellone da gioco
void Game::showBillboard()
{
char box[50];
char c[50];
c[0] = '\0';
int r = (numBoxes % N_COLUMNS == 0) ? 0 : 1;
int n = numBoxes / N_COLUMNS + r;
for(int i = 0; i < n; i++)
{
for (int j = 0; j < N_COLUMNS; j++)
{
int pos = i + j * n;
if (pos >= numBoxes)
{
continue;
}
add_color(box, boxes[pos]->getText(), boxes[pos]->getColor());
this->show_players_position(c,pos);
cout << (j > 0 ? "| " : " ");
cout << right << setfill(' ') << setw(numPlayers) << c;
cout << right << setw(2) << pos << '.' << left << setfill(' ') << setw(W_COLUMN) << box;
c[0] = '\0';
}
cout << endl;
}
}
//output finale
void Game::endGame()
{
currPlayer = prevPlayer();
separate();
showBillboard();
cout << endl;
for(int i = 0; i < numPlayers; ++i)
{
cout << "Giocatore " << i+1 << ". " << players[i]->getName()
<< " - Casella " << players[i]->getPos() << endl;
}
cout << endl << "Vince il giocatore " << currPlayer+1 << ". " << players[currPlayer]->getName() ;
}
Game::~Game()
{
}
| true |
e7f6501b57f5e3432a370c7a454151f5c72e38c2
|
C++
|
huynguy97/IP-Week11
|
/main.5952043835344930115.cpp
|
UTF-8
| 3,645 | 3.4375 | 3 |
[] |
no_license
|
#include <iostream>
#include<cassert>
#include<cmath>
#include<string>
//
//
using namespace std;
int power (int base, int exponent)
{
//
assert(exponent >= 0);
//
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
int power_efficient (int base, int exponent)
{
//
assert(exponent>=0);
//
if (exponent == 0)
return 1;
else if (exponent == 1)
return base;
else if (exponent % 2 == 0)
return power_efficient(base * base, exponent / 2);
else if((exponent % 2) != 0)
return base * power_efficient(base * base, (exponent - 1) / 2);
else;
}
//
bool palindrome1(string text, int unsigned i, int unsigned j)
{
//
assert(i>=0 && j>=0 && j<text.length());
//
if(text[i]!=text[j])
{
return false;
}
else if(i>j)
{
return true;
}
else
{
return palindrome1(text,i+1,j-1);
}
}
bool palindrome2(string text, int unsigned i, int unsigned j)
{
//
assert(i>=0 && j>=0 && j<text.length());
//
if(text[i]!=text[j]&& text[i]!=text[j]-32 && text[i]-32!=text[j])
{
return false;
}
else if(i>j)
{
return true;
}
else
{
return palindrome2(text,i+1,j-1);
}
}
bool palindrome3(string text, int unsigned i, int unsigned j)
{
//
assert(i>=0 && j>=0 && j < text.length());
//
if(i>j)
{
return true;
}
else
{
if((text[i]<65 || (text[i]>90 && text[i]<97) || text[i]>122) && !(text[j]<65 || (text[j]>90 && text[j]<97) || text[j]>122))
return palindrome3(text,i+1,j);
else if((text[j]<65 || (text[j]>90 && text[j]<97) || text[j]>122) && !(text[i]<65 || (text[i]>90 && text[i]<97) || text[i]>122))
return palindrome3(text,i,j-1);
else if((text[i]<65 || (text[i]>90 && text[i]<97) || text[i]>122) &&(text[j]<65 || (text[j]>90 && text[j]<97) || text[j]>122) )
return palindrome3(text,i+1,j-1);
else if (!(text[i]!=text[j] && text[i]!=text[j]-32 && text[i]-32!=text[j]))
return palindrome3(text,i+1,j-1);
else
return false;
}
}
bool match_chars (string chars, int unsigned i, string source, int unsigned j)
{
//
assert(j <= source.length() && i <= chars.length());
//
if (i == chars.length())
{
return true;
}
else if (j == source.length())
{
return false;
}
else if (chars[i] == source[j])
{
return match_chars(chars, i+1, source, j+1);
}
else if (chars[i] != source[j])
{
return match_chars(chars, i, source, j+1);
}
else;
}
int main()
{
//
//
//
//
return 0;
}
| true |
f104d2eaceb1aca918fcac38240c938b729b367f
|
C++
|
JanMalitschek/Gel
|
/Gel/Camera.cpp
|
UTF-8
| 1,991 | 2.78125 | 3 |
[] |
no_license
|
#include "Camera.h"
namespace Gel {
glm::vec3 Camera::position = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 Camera::up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 Camera::front = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 Camera::right = glm::normalize(glm::cross(up, front));
glm::mat4 Camera::projection = glm::perspective(RenderSettings::GetFieldOfView(),
RenderSettings::GetAspectRatio(),
RenderSettings::GetNearPlane(),
RenderSettings::GetFarPlane());
glm::mat4 Camera::view = glm::lookAt(position, position + front, up);
void Camera::SetPosition(glm::vec3 position) {
Camera::position = position;
}
glm::mat4 Camera::GetProjection() {
return projection;
}
glm::mat4 Camera::GetView() {
return view;
}
glm::mat4 Camera::GetUpdatedView() {
Camera::view = glm::lookAt(position, position + front, up);
return view;
}
void Camera::SetProjection(float fov, float aspectRatio, float nearPlane, float farPlane) {
Camera::projection = glm::perspective(fov, aspectRatio, nearPlane, farPlane);
}
void Camera::SetView(glm::vec3 position, glm::vec3 front, glm::vec3 up) {
Camera::view = glm::lookAt(position, position + front, up);
}
void Camera::Translate(glm::vec3 translation) {
float deltaTime = System::GetDeltaTime();
position += front * translation.z * deltaTime;
position += up * -translation.y * deltaTime;
position += right * -translation.x * deltaTime;
}
void Camera::Translate(float x, float y, float z) {
float deltaTime = System::GetDeltaTime();
glm::vec3 translation = glm::vec3(x, y, z);
position += front * translation.z * deltaTime;
position += up * -translation.y * deltaTime;
position += right * -translation.x * deltaTime;
}
void Camera::SetFront(glm::vec3 front) {
Camera::front = front;
}
void Camera::SetUp(glm::vec3 up) {
Camera::up = up;
}
void Camera::SetRight(glm::vec3 right) {
Camera::right = right;
}
glm::vec3 Camera::GetPosition() {
return position;
}
}
| true |
e0989383796a7271f6ec50ccf56fbd95f638d3da
|
C++
|
GAlmyre/PFE_Terrain
|
/include/Sphere.h
|
UTF-8
| 8,114 | 2.765625 | 3 |
[] |
no_license
|
#ifndef TERRAINTINTIN_SPHERE_H
#define TERRAINTINTIN_SPHERE_H
#include <Eigen/Geometry>
#include <QOpenGLShaderProgram>
#include "OpenGL.h"
class Point
{
public:
static void draw(GLFuncs *f, QOpenGLShaderProgram* prg, const Eigen::Vector3f& p)
{
unsigned int vertexBufferId;
f->glGenBuffers(1,&vertexBufferId);
f->glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f), p.data(), GL_STATIC_DRAW);
unsigned int vertexArrayId;
f->glGenVertexArrays(1,&vertexArrayId);
// bind the vertex array
f->glBindVertexArray(vertexArrayId);
f->glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
int vertex_loc = prg->attributeLocation("vtx_position");
f->glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
f->glEnableVertexAttribArray(vertex_loc);
glPointSize(10.f);
glDrawArrays(GL_POINTS,0,1);
f->glDisableVertexAttribArray(vertex_loc);
f->glBindVertexArray(0);
f->glBindBuffer(GL_ARRAY_BUFFER, 0);
f->glDeleteBuffers(1, &vertexBufferId);
f->glBindVertexArray(0);
f->glDeleteVertexArrays(1, &vertexArrayId);
}
};
class Line
{
public:
static void draw(GLFuncs *f, QOpenGLShaderProgram* prg, const Eigen::Vector3f& p1, const Eigen::Vector3f& p2)
{
Eigen::Vector3f mPoints[2] = {p1, p2};
unsigned int vertexBufferId;
f->glGenBuffers(1,&vertexBufferId);
f->glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f)*2, mPoints[0].data(), GL_STATIC_DRAW);
unsigned int vertexArrayId;
f->glGenVertexArrays(1,&vertexArrayId);
// bind the vertex array
f->glBindVertexArray(vertexArrayId);
f->glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
int vertex_loc = prg->attributeLocation("vtx_position");
f->glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
f->glEnableVertexAttribArray(vertex_loc);
glDrawArrays(GL_LINES,0,2);
f->glDisableVertexAttribArray(vertex_loc);
f->glBindVertexArray(0);
f->glBindBuffer(GL_ARRAY_BUFFER, 0);
f->glDeleteBuffers(1, &vertexBufferId);
f->glBindVertexArray(0);
f->glDeleteVertexArrays(1, &vertexArrayId);
}
};
class Sphere {
public:
Sphere() : _radius(0), _f(nullptr) {}
~Sphere() {
if (_f) {
_f->glDeleteVertexArrays(1, &_vao);
_f->glDeleteBuffers(6, _vbo);
}
}
void generate(float radius=1.f, int nU=40, int nV=40) {
_radius = radius;
int nVertices = (nU + 1) * (nV + 1);
int nTriangles = nU * nV * 2;
_vertices.resize(nVertices);
_normals.resize(nVertices);
_tangents.resize(nVertices);
_texCoords.resize(nVertices);
_colors.resize(nVertices);
_indices.resize(3*nTriangles);
for(int v=0;v<=nV;++v)
{
for(int u=0;u<=nU;++u)
{
float theta = u / float(nU) * M_PI;
float phi = v / float(nV) * M_PI * 2;
int index = u +(nU+1)*v;
Eigen::Vector3f vertex, tangent, normal;
Eigen::Vector2f texCoord;
// normal
normal[0] = sin(theta) * cos(phi);
normal[1] = sin(theta) * sin(phi);
normal[2] = cos(theta);
normal.normalize();
// position
vertex = normal * _radius;
// tangent
theta += M_PI_2;
tangent[0] = sin(theta) * cos(phi);
tangent[1] = sin(theta) * sin(phi);
tangent[2] = cos(theta);
tangent.normalize();
// texture coordinates
texCoord[1] = u / float(nU);
texCoord[0] = v / float(nV);
_vertices[index] = vertex;
_normals[index] = normal;
_tangents[index] = tangent;
_texCoords [index] = texCoord;
_colors[index] = Eigen::Vector3f(0.6f,0.2f,0.8f);
_bbox.extend(vertex);
}
}
int index = 0;
for(int v=0;v<nV;++v)
{
for(int u=0;u<nU;++u)
{
int vindex = u + (nU+1)*v;
_indices[index+0] = vindex;
_indices[index+1] = vindex+1 ;
_indices[index+2] = vindex+1 + (nU+1);
_indices[index+3] = vindex;
_indices[index+4] = vindex+1 + (nU+1);
_indices[index+5] = vindex + (nU+1);
index += 6;
}
}
}
void init(GLFuncs *funcs) {
bool genBuffers = (_f == nullptr);
_f = funcs;
if (genBuffers) {
_f->glGenVertexArrays(1, &_vao);
_f->glGenBuffers(6, _vbo);
}
_f->glBindVertexArray(_vao);
_f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[0]);
_f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int) * _indices.size(), _indices.data(), GL_STATIC_DRAW);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[1]);
_f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f) * _vertices.size(), _vertices.data(), GL_STATIC_DRAW);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[2]);
_f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f) * _colors.size(), _colors.data(), GL_STATIC_DRAW);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[3]);
_f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f) * _normals.size(), _normals.data(), GL_STATIC_DRAW);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[4]);
_f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector3f) * _tangents.size(), _tangents.data(), GL_STATIC_DRAW);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[5]);
_f->glBufferData(GL_ARRAY_BUFFER, sizeof(Eigen::Vector2f) * _texCoords.size(), _texCoords.data(), GL_STATIC_DRAW);
_f->glBindVertexArray(0);
}
void display(QOpenGLShaderProgram &shader) {
_f->glBindVertexArray(_vao);
_f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[0]);
int vertex_loc = shader.attributeLocation("vtx_position");
_f->glEnableVertexAttribArray(vertex_loc);
if(vertex_loc>=0){
_f->glEnableVertexAttribArray(vertex_loc);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[1]);
_f->glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
int color_loc = shader.attributeLocation("vtx_color");
if(color_loc>=0){
_f->glEnableVertexAttribArray(color_loc);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[2]);
_f->glVertexAttribPointer(color_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
int normal_loc = shader.attributeLocation("vtx_normal");
if(normal_loc>=0){
_f->glEnableVertexAttribArray(normal_loc);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[3]);
_f->glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
int tangent_loc = shader.attributeLocation("vtx_tangent");
if(tangent_loc>=0){
_f->glEnableVertexAttribArray(tangent_loc);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[4]);
_f->glVertexAttribPointer(tangent_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
int texCoord_loc = shader.attributeLocation("vtx_texcoord");
if(texCoord_loc>=0){
_f->glEnableVertexAttribArray(texCoord_loc);
_f->glBindBuffer(GL_ARRAY_BUFFER, _vbo[5]);
_f->glVertexAttribPointer(texCoord_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
}
glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0);
if(vertex_loc>=0)
_f->glDisableVertexAttribArray(vertex_loc);
if(color_loc>=0)
_f->glDisableVertexAttribArray(color_loc);
if(normal_loc>=0)
_f->glDisableVertexAttribArray(normal_loc);
if(tangent_loc>=0)
_f->glDisableVertexAttribArray(tangent_loc);
if(texCoord_loc>=0)
_f->glDisableVertexAttribArray(texCoord_loc);
_f->glBindVertexArray(0);
}
float radius() const { return _radius; }
public:
Eigen::Affine3f _transformation;
private:
GLFuncs *_f;
GLuint _vao;
GLuint _vbo[6];
std::vector<int> _indices; /** vertex indices */
std::vector<Eigen::Vector3f> _vertices; /** 3D positions */
std::vector<Eigen::Vector3f> _colors; /** colors */
std::vector<Eigen::Vector3f> _normals; /** 3D normals */
std::vector<Eigen::Vector3f> _tangents; /** 3D tangent to surface */
std::vector<Eigen::Vector2f> _texCoords; /** 2D texture coordinates */
Eigen::AlignedBox3f _bbox;
float _radius;
};
#endif //TERRAINTINTIN_SPHERE_H
| true |
c8818dda1c8aaeca7821927741e88581c1cd7e34
|
C++
|
fuqinho/ChallengeBook
|
/quiz/052_01Knapsack/main.cpp
|
UTF-8
| 893 | 2.96875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define dump(x) cerr << #x << " = " << (x) << endl;
int solve(int N, vector<int>& v, vector<int>& w, int W) {
// dp[i][j]: i番目までの品物から合計j以下の重さになるように
// 選んだ時の価値の最大値
vector<vector<int> > dp(N+1, vector<int>(W+1, 0));
for (int i = 0; i < N; i++)
for (int j = 0; j <= W; j++)
if (j < w[i])
dp[i+1][j] = dp[i][j];
else
dp[i+1][j] = max(dp[i][j], dp[i][j-w[i]] + v[i]);
return dp[N-1][W];
}
int main() {
int N; cin >> N;
vector<int> v(N), w(N);
REP(i, N) cin >> w[i] >> v[i];
int W; cin >> W;
int answer = solve(N, v, w, W);
cout << "Answer: " << answer << endl;
}
| true |
d6e44f8b51f4c63d736f1b9561c17fb8c4893754
|
C++
|
tmyksj/atcoder
|
/AtCoder Beginner Contest 165/C - Many Requirements/main.cpp
|
UTF-8
| 935 | 2.890625 | 3 |
[] |
no_license
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
long long solve(int n, int m, int q,
vector<int>& a, vector<int>& b, vector<int>& c, vector<int>& d,
vector<int>& h) {
if (n == static_cast<int>(h.size())) {
long long res = 0;
for (int i = 0; i < q; i++) {
if (h[b[i] - 1] - h[a[i] - 1] == c[i]) {
res += d[i];
}
}
return res;
}
long long res = 0;
for (int i = (h.size() == 0 ? 1 : h[h.size() - 1]); i <= m; i++) {
h.push_back(i);
res = max(res, solve(n, m, q, a, b, c, d, h));
h.pop_back();
}
return res;
}
int main() {
int n, m, q;
cin >> n >> m >> q;
vector<int> a(q), b(q), c(q), d(q);
for (int i = 0; i < q; i++) {
cin >> a[i] >> b[i] >> c[i] >> d[i];
}
vector<int> h(0);
cout << solve(n, m, q, a, b, c, d, h) << endl;
}
| true |
d8771720f8ec9aa8df8877e00a493f0d42f7a34b
|
C++
|
Counterfeit093/Stuff
|
/Library.cpp
|
UTF-8
| 4,458 | 3.234375 | 3 |
[] |
no_license
|
#include <iostream>
#include "Library.h"
#include <windows.h>
#include <fstream>
#include <cstdlib>
using namespace std;
Library::Library()
{
takeABook = 0;
numberOfAddedBooks = 0;
}
void Library::addBook(string title, string author)
{
if(numberOfAddedBooks<listOfBooks)
{
allBooks[numberOfAddedBooks] = Book(title,author);
numberOfAddedBooks++;
// cout << "Dodano Ksiazke: " << Ttitle << ", "<<Aauthor<<endl;
}
else
{
cout << "Maksymalna liczba ksiazek dodana" << endl;
}
}
void Library::takeBook()
{
cout<<endl;
cout << "Wybierz ksiazke z listy ksiazek dostepnych do wypozyczenia (lub 0 aby wyjsc):" << endl << endl;
cin >> takeABook;
if(takeABook < 0 || takeABook > numberOfAddedBooks)
{
if(takeABook != 0)
{
takeABook = 0;
cout << "Nie ma takiej ksiazki" << endl << endl;
system("pause");
}
}
}
void Library::cleanBase()
{
fstream file;
file.open("ListOfBooks.txt",ios::out);
file.close();
}
void Library::readBooksFromBase()
{
string a[20];
string b[20];
string something[20];
fstream file1;
string line1;
int lineNumber=1;
int numberOfBook=0;
file1.open("ListOfBooks.txt",ios::in);
if(file1.good()==false)
{
cout<<"Plik zostal uszkodzony badz nie istnieje"<<endl;
exit(0);
}
while(getline(file1,line1))
{
switch(lineNumber)
{
case 1: a[lineNumber]=line1; break;
case 2: b[lineNumber]=line1; break;
case 3: something[lineNumber]=line1; break;
}
if(lineNumber==3){lineNumber=0;numberOfBook++;}
lineNumber++;
}
file1.close();
for(int i=0; i<=19; i++)
{
cout<<a[i]<<endl;
cout<<b[i]<<endl;
cout<<something[i]<<endl;
}
}
void Library::sendUsersToBase()
{
}
void Library::showAllBooksInBase()
{
int i = 0;
for(i = i; i < numberOfAddedBooks; i++)
{
cout << i+1 <<". "<<endl;
allBooks[i].show();
cout << endl;
}
cout << endl << "Wszystkich ksiazek: " << numberOfAddedBooks << endl;
}
void Library::BookIsTaken()
{
int i = 0;
for(i = i; i < listOfBooks; i++)
{
allBooks[i].show();
allBooks[i].BookIsTaken();
cout<<endl;
}
}
void Library::sendBookToBase()
{
for(int i=0;i<listOfBooks;i++)
{
allBooks[i].sendInformationsAboutBook();
}
}
void Library::showPiecesBooks()
{
int i = 0;
for(i = i; i < listOfBooks; i++)
{
allBooks[i].show();
allBooks[i].showPiecesBooks();
}
}
void Library::showTakenBooks()
{
int i = 0;
for(i = i; i < listOfBooks; i++)
{
allBooks[i].show();
allBooks[i].showTakenBooks();
}
}
void Library::borrowBook()
{
cout << "Wypozycz:" << endl << endl << endl;
showAllBooksInBase();
takeBook();
if(takeABook != 0)
{
allBooks[takeABook-1].borrowBook();
}
}
void Library::cancelBorrowing()
{
cout << "Anuluj wypozyczanie:" << endl << endl << endl;
showAllBooksInBase();
takeBook();
if(takeABook != 0)
{
allBooks[takeABook-1].cancelBorrowing();
}
}
void Library::checkBorrow()
{
cout << "Sprawdz wypozyczanie:" << endl << endl << endl;
showAllBooksInBase();
takeBook();
if(takeABook != 0)
{
allBooks[takeABook-1].checkBorrow();
}
}
| true |