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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
103adaf51c271c083a65e6aa7daed4ddada6f872 | C++ | keshav1999/c_plus_plus_Programming | /day9/bubblesortrecursion.cc | UTF-8 | 557 | 3.265625 | 3 | [] | no_license | #include<iostream>
using namespace std;
void input( int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
}
void output( int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
cout << arr[i] << " ";
}
}
void bubblesort(int arr[],int n)
{
if(n<=0)
{
return;
}
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
swap(arr[j],arr[j+1]);
}
}
bubblesort(arr,n-1);
}
int main()
{
int N,A[100];
cin>>N;
input(A,N);
bubblesort(A,N);
output(A,N);
} | true |
4a78527a45fb63b29f291e3575ddc4fd9ed64b9d | C++ | chrisdenado/suanfa-jichu | /chap3-iteration/c3-smallgame.cpp | UTF-8 | 2,232 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int To[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
bool isIn(int x, int y, int w, int h)
{
return ( x>-1 && x<h+2 && y>-1 && y<w+2 );
}
void search(const vector<vector<int>> &card, vector<vector<int>> &mark, int &min_step, int step, int forward, \
int cur_x, int cur_y, int end_x, int end_y, int w, int h)
{
if(step >= min_step) return;
if(cur_x==end_x && cur_y==end_y)
{
if(min_step > step) min_step = step;
return;
}
for(int i=0; i<4; i++)
{
int x = cur_x + To[i][0];
int y = cur_y + To[i][1];
if( isIn(x,y,w,h) && ( (card[x][y] != 1 && mark[x][y] != 1) || (x==end_x && y==end_y) )) //mark的作用避免在i 和i+1之间产生死循环
{
mark[x][y] = 1;
if(i == forward) search(card, mark, min_step, step, i, x, y, end_x, end_y, w, h);
else search(card, mark, min_step, step+1, i, x, y, end_x, end_y, w, h);
mark[x][y] = 0;
}
}
}
int main()
{
int w,h;
cin>>w>>h;
int board_num=0;
char in;
while( w!=0 && h!=0 )
{
vector<vector<int>> card(h+2, vector<int>(w+2, 0)), mark(h+2, vector<int>(w+2, 0));
for(int i=1; i<h+1; i++)
{
getchar();
for(int j=1; j<w+1; j++)
{
in = getchar();
if(in == 'X') card[i][j] = 1;
}
}
int begin_x, begin_y, end_x, end_y;
cin>>begin_y>>begin_x>>end_y>>end_x;
vector<int> temp;
while( begin_x!=0 &&begin_y!=0 && end_x!=0 && end_y!=0 )
{
int min_step = 0x7fffffff, step = 0;
search(card, mark, min_step, step, -1, begin_x, begin_y, end_x, end_y, w, h);
temp.push_back(min_step);
cin>>begin_y>>begin_x>>end_y>>end_x;
}
cin>>w>>h;
cout<<"Board #"<<++board_num<<":"<<endl;
for(int i=0; i<temp.size(); i++)
{
if(temp[i] != 0x7fffffff) cout<<"Pair "<<i+1<<": "<<temp[i]<<" segments."<<endl;
else cout<<"Pair "<<i+1<<": "<<"impossible."<<endl;
}
cout<<endl;
}
return 0;
}
| true |
6b90cc440b601d2d453a0fa58e8fdc00e0ea92de | C++ | benpauldev/OSU-CS165 | /Assignment 4/Project 4.c/Project 4.c/Student.cpp | UTF-8 | 414 | 2.78125 | 3 | [] | no_license |
/*
Author: Benjamin Fondell
Date: 1/31/2017
Description: Project 4.c Student.cpp
*/
#include "Student.hpp"
#include <string>
using namespace std;
Student::Student(string studentName, double studentScore)
{
name = studentName;
score = studentScore;
}
string Student :: getName()
{
return name;
}
double Student:: getScore()
{
return score;
}
/*
Description: Project 4.c Student.cpp
*/
| true |
6b09df0d2e4da1b0d671466d4cf20620103887f3 | C++ | LegatAbyssWalker/OpenGL-Tests | /OpenGL First Test/World.cpp | UTF-8 | 1,138 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "World.h"
World::World(GLWindow& glWindow) : glWindow(glWindow) {
// Chunk generation
GLsizei TOTAL_CHUNK_AMOUNT = 2; // MULTIPLE OF 2
GLsizei TOTAL_TREE_AMOUNT_PER_CHUNK = 5;
for (GLsizei x = 0; x < TOTAL_CHUNK_AMOUNT / 2; x++) {
for (GLsizei z = 0; z < TOTAL_CHUNK_AMOUNT / 2; z++) {
chunkVector.emplace_back(new ChunkGenerator(glm::vec3(x * CHUNK_SIZE, NULL, z * CHUNK_SIZE), TOTAL_TREE_AMOUNT_PER_CHUNK));
}
}
/*-------------------------------------------------------------------------------------------------------------------*/
}
void World::update() {
for (auto& chunk : chunkVector) {
chunk->update();
}
}
void World::render(glm::mat4 viewMatrix) {
// Projection
glm::mat4 projection = glm::perspective(glm::radians(45.f), (GLfloat)glWindow.getBufferWidth() / glWindow.getBufferHeight(), 0.1f, 100.f);;
for (auto& chunk : chunkVector) {
chunk->render(glWindow, viewMatrix, projection);
}
}
glm::mat4 World::getProjectionMatrix() {
return glm::perspective(glm::radians(45.f), (GLfloat)glWindow.getBufferWidth() / glWindow.getBufferHeight(), 0.1f, 100.f);
}
| true |
382e8b4ec909a3ce44d8f33aa6ba7aa944f0227d | C++ | cynthia-1999/crypto-accumulators | /lib/utils/ThreadPool.cpp | UTF-8 | 938 | 3.265625 | 3 | [
"MIT"
] | permissive |
#include <utils/ThreadPool.hpp>
void Worker::operator()()
{
while(true)
{
std::unique_lock<std::mutex> lock(pool.queue_mutex);
while(!pool.stop && pool.tasks.empty())
pool.condition.wait(lock);
if(pool.stop && pool.tasks.empty())
return;
std::function<void()> task(pool.tasks.front());
pool.tasks.pop();
lock.unlock();
task();
}
}
//Default constructor constructs the pool with 1 thread (no concurrency)
ThreadPool::ThreadPool() : ThreadPool(1) {}
// the constructor just launches some amount of workers
ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.push_back(std::thread(Worker(*this)));
}
// the destructor joins all threads
ThreadPool::~ThreadPool()
{
stop = true;
condition.notify_all();
for(size_t i = 0;i<workers.size();++i)
workers[i].join();
}
| true |
8faa520480df581f66fb281402bfe7cb2c490e15 | C++ | Mourx/RTS | /RTS/RTS/Node.h | UTF-8 | 212 | 2.78125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
class Node {
public:
Node();
Node* Adjacent[4]; // Up, Right, Down, Left
int travelCost;
int totalTravelCost;
float x, y;
Node* nextNode;
};
| true |
b0a342bc648834123a6ef32d74dd9feaf3810f2c | C++ | andy-yang-1/BookStore | /src/unrolled_linked_list.cpp | UTF-8 | 6,347 | 3.046875 | 3 | [] | no_license | #include "unrolled_linked_list.h"
List::List() {}
List::List(const char *file_name)
{
strcpy( filename , file_name ) ;
}
void List::add_key(element &add_element, pair<bool, pair<int, int>> search_pos)
{
block temp_block ;
temp_block.get_block( getKeyType(filename) , search_pos.second.first ) ;
if ( search_pos.first == 1 ) cerr << "add_key: existing key" << endl ;
for ( int i = temp_block.length ; i > search_pos.second.second ; i-- ){
temp_block.data[i] = temp_block.data[i-1] ;
}// 将所有数据位移一格
temp_block.data[search_pos.second.second] = add_element ;
temp_block.length++ ;
temp_block.put_block(getKeyType(filename),temp_block.pos) ;
if ( temp_block.length == BLOCK_SIZE ){
this->split_block( getKeyType(filename) , temp_block.pos ) ;
}
}
void List::del_key(pair<bool, pair<int, int>> search_pos)
{
block temp_block , nxt_block ;
temp_block.get_block( getKeyType(filename) , search_pos.second.first ) ; // todo get_block函数在读取时出现异常
for ( int i = search_pos.second.second ; i < temp_block.length ; i++ ){
temp_block.data[i] = temp_block.data[i+1] ;
}
temp_block.length-- ;
temp_block.put_block(getKeyType(filename),temp_block.pos) ;
if ( temp_block.down != -1 ){
nxt_block.get_block( getKeyType(filename) , temp_block.down ) ;
if ( temp_block.length + nxt_block.length < MERGE_LIMIT ){
this->merge_block( getKeyType(filename) , temp_block.pos , nxt_block.pos ) ;
}
}
}
pair<bool, pair<int, int> > List::search_key(key_type KeyType, element &search_element)
{
block temp_block ;
temp_block.get_block( KeyType , 0 ) ; // todo initialize时建立起第一批block
while (true){
if ( search_element < temp_block || search_element == temp_block || temp_block.down == -1 ) break ;
temp_block.get_block( KeyType , temp_block.down ) ;
}
if ( search_element == temp_block ) {
return pair< bool , pair<int,int> > ( {1,{temp_block.pos,0}} ) ;
}
if ( search_element < temp_block && temp_block.up != -1 ) {
temp_block.get_block( KeyType , temp_block.up ) ;
}
int counter = 0 ;
while ( counter < temp_block.length ){
if ( search_element == temp_block.data[counter] ){ // 找到目标
return pair< bool , pair<int,int> > ( {1,{temp_block.pos,counter}} ) ;
}
if ( search_element < temp_block.data[counter] ){ // 目标不存在
return pair< bool , pair<int,int> > ( { 0 , {temp_block.pos,counter} } ) ;
}
if ( search_element > temp_block.data[counter] ){
counter++ ;
}
}
return pair< bool , pair<int,int> > ( {0,{temp_block.pos,counter}} ) ; // 未找到,在其最后一位
}
int List::get_key(pair<bool, pair<int, int>> search_pos)
{
block temp_block ;
temp_block.get_block( getKeyType(filename) , search_pos.second.first ) ;
return temp_block.data[search_pos.second.second].offset ;
}
void List::split_block(key_type KeyType, int offset)
{
block origin_block , temp_block , nxt_block ;
origin_block.get_block(KeyType,offset) ;
for ( int i = BLOCK_SIZE / 2 ; i < BLOCK_SIZE ; i++ ){
temp_block.data[i-BLOCK_SIZE/2] = origin_block.data[i] ;
}
temp_block.length = BLOCK_SIZE / 2 ;
origin_block.length = BLOCK_SIZE / 2 ;
int block_num = get_block_num(KeyType) ;
temp_block.pos = block_num ;
temp_block.up = origin_block.pos ;
if ( origin_block.down == -1 ){
origin_block.down = temp_block.pos ;
origin_block.put_block(KeyType,origin_block.pos) ;
temp_block.put_block(KeyType,temp_block.pos) ;
}else{
nxt_block.get_block(KeyType,origin_block.down) ;
nxt_block.up = temp_block.pos ;
temp_block.down = nxt_block.pos ;
origin_block.down = temp_block.pos ;
origin_block.put_block(KeyType,origin_block.pos) ;
temp_block.put_block(KeyType,temp_block.pos) ;
nxt_block.put_block(KeyType,nxt_block.pos) ;
}
change_block_num(KeyType,++block_num) ;
}
void List::merge_block(key_type KeyType, int first_block_pos, int second_block_pos)
{
block up_block , down_block , nxt_block ;
up_block.get_block(KeyType,first_block_pos) ;
down_block.get_block(KeyType,second_block_pos) ;
for ( int i = 0 ; i < down_block.length ; i++ ){
up_block.data[i+up_block.length] = down_block.data[i] ;
}
up_block.down = down_block.down ;
up_block.length += down_block.length ;
if ( down_block.down == -1 ){
up_block.put_block(KeyType,up_block.pos) ;
}else{
nxt_block.get_block(KeyType,down_block.down) ;
nxt_block.up = up_block.pos ;
up_block.put_block(KeyType,up_block.pos) ;
nxt_block.put_block(KeyType,nxt_block.pos) ;
}
}
void List::show_key(key_type KeyType, const char *main_key)
{
element searched_element( main_key , "" , 0 ) ;
pair< bool , pair<int,int> > start_pos = search_key(KeyType,searched_element) ;
block temp_block ;
temp_block.get_block(KeyType,start_pos.second.first) ;
if ( !temp_block.data[start_pos.second.second].equal_with(searched_element) ){
if ( start_pos.second.second == temp_block.length && temp_block.down != -1 ){
temp_block.get_block(KeyType,temp_block.down) ;
if ( temp_block.data[0].equal_with(searched_element) ){
start_pos.second.second = 0 ;
}else{ cout << endl ; return ;}
}else{ cout << endl ; return ; }
}// todo 在 complexTest2 2.in 91行输入出现了无端空行
int start_point = start_pos.second.second , offset ;
book temp_book ;
while (true){
for ( int i = start_point ; i < temp_block.length ; i++ ){
if ( !temp_block.data[i].equal_with(searched_element) ) return ;
temp_book.get_book(temp_block.data[i].offset) ;
temp_book.print_book() ;
}
if ( temp_block.down == -1 ) return ;
temp_block.get_block( KeyType , temp_block.down ) ;
start_point = 0 ;
}
}
| true |
855718f98aff81130826372f623e57dd0c98a417 | C++ | thetruegamer/zork_game | /zork/Creature.cpp | UTF-8 | 2,462 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include "Creature.h"
#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_utils.hpp"
#include "../rapidxml/rapidxml_print.hpp"
using namespace std;
using namespace rapidxml;
Creature::Creature(xml_node<> * creatureTag){
xml_node<> * creatureElement = NULL;
deleted = 0;
for(creatureElement = creatureTag->first_node(); creatureElement; creatureElement = creatureElement->next_sibling()){
if(strcmp(creatureElement->name(),"name") == 0){
name = creatureElement->value();
}
if(strcmp(creatureElement->name(),"status") == 0){
status = creatureElement->value();
}
if(strcmp(creatureElement->name(),"description") == 0){
description = creatureElement->value();
}
if(strcmp(creatureElement->name(),"vulnerability") == 0){
vulnerability.push_back(creatureElement->value());
}
if(strcmp(creatureElement->name(),"attack") == 0){
xml_node<> * attackElement = NULL;
//cout << "hi" << endl;
for(attackElement = creatureElement->first_node(); attackElement; attackElement = attackElement->next_sibling()){
if(strcmp(attackElement->name(),"condition") == 0){
xml_node<> * conditionElement = NULL;
//cout << "hi" << endl;
for(conditionElement = attackElement->first_node(); conditionElement; conditionElement = conditionElement->next_sibling()){
if(strcmp(conditionElement->name(),"object") == 0){
creature_condition.object = conditionElement->value();
//cout << "object created" << endl;
}
if(strcmp(conditionElement->name(),"status") == 0){
creature_condition.status = conditionElement->value();
}
}
attack.condition = creature_condition;
}
if(strcmp(attackElement->name(),"print") == 0){
attack.print = attackElement->value();
}
if(strcmp(attackElement->name(),"action") == 0){
attack.action.push_back(attackElement->value());
}
}
}
if(strcmp(creatureElement->name(),"trigger") == 0){
Trigger newTrigger = Trigger(creatureElement);
trigger.push_back(newTrigger);
cout << "trigger created for creature" << endl;
}
}
}
void Creature::setVulnerability(string vulnerability){
(this->vulnerability).push_back(vulnerability);
}
vector<string> Creature::getVulnerability(){
return vulnerability;
}
void Creature::setAttack(Condition, string, vector<string>){
}
Attack Creature::getAttack(){
return attack;
} | true |
c7694360603f941acbcaf98a83345b73d301fb73 | C++ | pamtabak/DistributedSystems | /IPC/Sockets/Producer/main.cpp | UTF-8 | 3,089 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#define RAND(min, max) rand() % (max - min + 1) + min
#define BUFFER_SIZE 256
#define PORT_NO 666
#define MAX_CONNECTIONS 5
/**
* Returns a random number larger than the last ont generated and between the min/max value
* @param[in] lastRandomNumber, min, max
* @return int random number
*/
int getIncreasingRandomNumber(int min, int max)
{
srand(time(NULL));
return RAND(min, max);;
}
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockFileDesc, newSockFileDesc, response, indexOfZero;
socklen_t clientLen;
char buffer[BUFFER_SIZE];
struct sockaddr_in serverAddr, clientAddr;
if(argc != 2)
{
std::cout << "Wrong parameters." << std::endl;
return EXIT_FAILURE;
}
sockFileDesc = socket(AF_INET, SOCK_STREAM, 0);
if(sockFileDesc < 0)
{
error((char *) "ERROR opening socket");
}
// bzero() sets all values in a buffer to zero
bzero((char *) &serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT_NO);
serverAddr.sin_addr.s_addr = INADDR_ANY;
// bind() binds a socket to an address
if(bind(sockFileDesc, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
{
error((char *) "ERROR binding socket");
}
// listen() allows the process to listen on the socket for connections. The second argument is the
// number of connections that can be waiting while the process is handling a particular connection
listen(sockFileDesc, MAX_CONNECTIONS);
clientLen = sizeof(clientAddr);
// accept() causes the process to block until a client connects to the server
newSockFileDesc = accept(sockFileDesc, (struct sockaddr *) &clientAddr, &clientLen);
if(newSockFileDesc < 0)
{
error((char *) "ERROR accepting client connection");
}
indexOfZero = atoi(argv[1]);
int delta, min, max, randomNumber;
delta = std::numeric_limits<int>::max() / indexOfZero;
min = 0;
max = delta;
for(int i = 0; i < indexOfZero; i++)
{
randomNumber = getIncreasingRandomNumber(min, max);
min += delta;
max += delta;
std::string s = std::to_string(randomNumber);
const char * c = s.c_str();
response = write(newSockFileDesc, c, s.size());
if(response < 0)
{
error((char *) "ERROR writing to socket");
}
bzero(buffer, BUFFER_SIZE);
// read() blocks until there is something for it to read in the socket
response = read(newSockFileDesc, buffer, BUFFER_SIZE - 1);
if(response < 0)
{
error((char *) "ERROR reading from socket");
}
std::cout << "The number " << s << " is prime: " << buffer << std::endl;
}
response = write(newSockFileDesc, "0", 1);
if(response < 0)
{
error((char *) "ERROR writing to socket");
}
close(newSockFileDesc);
close(sockFileDesc);
return 0;
} | true |
40ce8a7dbe0f948b44156b34abf6a9326cd64d28 | C++ | Tanmoytkd/programming-projects | /Contest Participations/Mara 5/mnew.cpp | UTF-8 | 1,634 | 2.671875 | 3 | [] | no_license | using namespace std;
#include <bits/stdc++.h>
bool valid(vector<vector<string> > &c, const string &w) {
for (int i = 0; i < c.size(); ++i) {
int bad = true;
for (int j = 0; j < 3; ++j)
if (c[i][j].find(w[j]) == string::npos)
bad = false;
if (bad)
return false;
}
return true;
}
char add(char c) {
int a = c - 'a';
a = (a + 1) % 26;
return a + 'a';
}
char sub(char c) {
int a = c- 'a';
a = (a + 25) % 26;
return a+ 'a';
}
void solve() {
string from, to;
cin >> from >> to;
int c;
cin >> c;
vector<vector<string> > ct(c, vector<string>(3));
for (int i = 0; i < c; ++i)
for (int j = 0; j < 3; ++j)
cin >> ct[i][j];
if (!valid(ct, from) || !valid(ct, to)) {
printf("-1\n");
return;
}
queue<pair<string, int> > q;
q.push(make_pair(from, 0));
set<string> seen;
while (!q.empty()) {
string cur = q.front().first;
int dist = q.front().second;
q.pop();
if (cur == to) {
printf("%d\n", dist);
return;
}
if (seen.count(cur))
continue;
seen.insert(cur);
for (int i = 0; i < 3; ++i) {
string next = cur;
next[i] = add(cur[i]);
if (valid(ct, next))
q.push(make_pair(next, dist + 1));
next[i] = sub(cur[i]);
if (valid(ct, next))
q.push(make_pair(next, dist + 1));
}
}
printf("-1\n");
}
int main() {
freopen("i.txt", "r", stdin);
freopen("test.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
printf("Case %d: ", i + 1);
solve();
}
return 0;
}
| true |
918ea9837e22a30d41da6428fa894dddedcad69e | C++ | Dukeboys/open-dis | /old/tags/2.1/cpp/DIS/Marking.cpp | UTF-8 | 1,419 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <DIS/Marking.h>
using namespace DIS;
Marking::Marking():
_characterSet(0)
{
}
Marking::~Marking()
{
}
unsigned char Marking::getCharacterSet() const
{
return _characterSet;
}
void Marking::setCharacterSet(unsigned char pX)
{
_characterSet = pX;
}
char* Marking::getCharacters()
{
return _characters;
}
const char* Marking::getCharacters() const
{
return _characters;
}
void Marking::setCharacters(const char* x)
{
for(int i = 0; i < 11; i++)
{
_characters[i] = x[i];
}
}
void Marking::marshal(DataStream& dataStream) const
{
dataStream << _characterSet;
for(size_t idx = 0; idx < 11; idx++)
{
dataStream << _characters[idx];
}
}
void Marking::unmarshal(DataStream& dataStream)
{
dataStream >> _characterSet;
for(size_t idx = 0; idx < 11; idx++)
{
dataStream >> _characters[idx];
}
}
bool Marking::operator ==(const Marking& rhs) const
{
bool ivarsEqual = true;
if( ! (_characterSet == rhs._characterSet) ) ivarsEqual = false;
for(char idx = 0; idx < 11; idx++)
{
if(!(_characters[idx] == rhs._characters[idx]) ) ivarsEqual = false;
}
return ivarsEqual;
}
int Marking::getMarshalledSize() const
{
int marshalSize = 0;
marshalSize = marshalSize + 1; // _characterSet
marshalSize = marshalSize + 11 * 1; // _characters
return marshalSize;
}
| true |
81b18b440eda81d8a98c530d171b6a5a5623ea7e | C++ | chrispiech/cs106b-fall-2016-website | /lectures/6-Sets_Maps/code/anagrams/src/anagrams.cpp | UTF-8 | 1,560 | 3.546875 | 4 | [
"MIT"
] | permissive | /*
* CS 106B, Chris Piech
* This program demonstrates the use of the Stanford C++ Set class.
* A set is a collection without duplicates that efficiently supports
* the core operations of adding, removing, and searching for elements.
*/
#include <fstream>
#include <iostream>
#include <iomanip>
#include "console.h"
#include "hashmap.h"
#include "map.h"
#include "set.h"
#include "simpio.h"
#include "filelib.h"
#include "lexicon.h"
using namespace std;
string sortLetters(string s);
int main() {
cout << "Anagrams" << endl;
Map<string, Set<string> > anagram;
Lexicon scrabbleLexicon("scrabble-dictionary.txt");
for(string word : scrabbleLexicon){
string sorted = sortLetters(word);
anagram[sorted].add(word);
}
// repeatedly prompt the user for words to look up in the map
while (true) {
string word = toLowerCase(getLine("Type a word [or Enter to quit]: "));
if (word == "") {
break;
} else {
string sorted = sortLetters(word);
for(string found : anagram[sorted]) {
cout << found << endl;
}
}
}
return 0;
}
//bbaacc -> aabbcc
/*
* Returns a canonical version of the given word
* with its letters arranged in alphabetical order.
* For example, sortLetters("banana") returns "aaabnn".
* This code was provided by the instructor as-is; we didn't write it in class.
*/
string sortLetters(string s) {
sort(s.begin(), s.end()); // sort function comes from C++ STL libraries
return s;
}
| true |
ab28cf37b4d2d761fdb5220e09ef754f5b5510ee | C++ | carloscarretero/Minotauro | /Algoritmo.ino | UTF-8 | 7,210 | 2.765625 | 3 | [] | no_license | /*
* -------------------------------------------------------------------------
* | Maze solving robot algorithm |
* | Authors: Carlos Carretero Aguilar, Rafael Moreno Anarte |
* | Date: 11 - 16 - 2015 |
* | Version: 1.00 |
* | Description:
* -------------------------------------------------------------------------
*/
#include "components.h"
#include <Servo.h>
#include "String.h"
//Variables globales:
int vector_valores[4]; // Para la toma de decisiones.
int pos_actual=0; // Esta es la posición hacia la que está mirando el minotauro en este momento
// por defecto empieza mirando hacia arriba.
int pos_siguiente;
int ejeX = 4, ejeY = 4; // Definimos la posición inicial.
int PRIORIDAD_0 = 3; // Prioridad MAX
int PRIORIDAD_1 = 2;
int PRIORIDAD_2 = 0;
int PRIORIDAD_3 = 1; // Priorida MIN
Engines engines(5,6,10,9,255,180);
Led led(11,12,13);
Sharp sharp(A3,7);
mySerial myserial;
Battery battery(A6);
myBluetooth mybluetooth;
int maze[5][5][4] = {};
void setup()
{
Serial1.begin(9600);
myserial.setup();
engines.setup();
sharp.setup();
led.setup();
}
void observar()
{
//Esto lo hará siempre y siempre bien.
maze[ejeX][ejeY][pos_actual] = sharp.lookFront();
if(maze[ejeX][ejeY][pos_actual]) // Si es != 0
mybluetooth.sendWall(pos_actual);
//Las otras opciones dependen de la pos_actual
if(pos_actual == 0) //Estamos mirando hacia arriba
{
maze[ejeX][ejeY][2] = sharp.lookLeft();
if(maze[ejeX][ejeY][2]) // Si es != de 0
mybluetooth.sendWall(2);
//ard.posInicial(); //Volvemos a la posición inicial
maze[ejeX][ejeY][3] = sharp.lookRight();
if(maze[ejeX][ejeY][3]) // Si es != de 0
mybluetooth.sendWall(3);
}
else
if(pos_actual == 1) //Mirando hacia abajo
{
maze[ejeX][ejeY][3] = sharp.lookLeft();
if(maze[ejeX][ejeY][3]) // Si es != 0
mybluetooth.sendWall(3);
//ard.posInicial(); //Volvemos a la posición inicial
maze[ejeX][ejeY][2] = sharp.lookRight();
if(maze[ejeX][ejeY][2]) // Si es != 0
mybluetooth.sendWall(2);
}
else
if(pos_actual == 2)
{
maze[ejeX][ejeY][1] = sharp.lookLeft();
if(maze[ejeX][ejeY][1]) // Si es != 0
mybluetooth.sendWall(1);
//ard.posInicial(); //Volvemos a la posición inicial
maze[ejeX][ejeY][0] = sharp.lookRight();
if(maze[ejeX][ejeY][0]) // Si es != 0
mybluetooth.sendWall(0);
}
else
if(pos_actual == 3)
{
maze[ejeX][ejeY][0] = sharp.lookLeft();
if(maze[ejeX][ejeY][0]) // Si es != 0
mybluetooth.sendWall(0);
//ard.posInicial(); //Volvemos a la posición inicial
maze[ejeX][ejeY][1] = sharp.lookRight();
if(maze[ejeX][ejeY][1]) // Si es != 0
mybluetooth.sendWall(1);
}
}
int decide_camino()
{
if(vector_valores[PRIORIDAD_0] == 0)
return PRIORIDAD_0;
else
if(vector_valores[PRIORIDAD_1] == 0)
return PRIORIDAD_1;
else
if(vector_valores[PRIORIDAD_2] == 0)
return PRIORIDAD_2;
else
if(vector_valores[PRIORIDAD_3] == 0)
return PRIORIDAD_3;
else
{
int i;
for(i=0;vector_valores[i]!=5;++i){}
return i; // Si no hay 5, puede haber bucle infinito. Puede solucionarse con un || i >= 4
}
}
void pivotar()
{
int pivote =0;
if(pos_actual == 0)
switch (pos_siguiente)
{
case 1: //queremos hacer un giro de 180
pivote = 2;
break;
case 2:
pivote = 0;
break;
case 3:
pivote = 1;
break;
}
else
if(pos_actual == 1)
switch (pos_siguiente)
{
case 0: //queremos hacer un giro de 180
pivote = 2;
break;
case 2:
pivote = 1;
break;
case 3:
pivote = 0;
break;
}
else
if(pos_actual == 2)
switch (pos_siguiente)
{
case 0:
pivote = 1;
break;
case 1:
pivote = 0;
break;
case 3:
pivote = 2;//queremos hacer un giro de 180
break;
}
else
if(pos_actual == 3)
switch (pos_siguiente)
{
case 0:
pivote = 0;
break;
case 1:
pivote = 1;
break;
case 2:
pivote = 2;//queremos hacer un giro de 180
break;
}
engines.pivot(pivote);
}
//método avanzar (ejecutar movimiento)
void avanzar ()
{
engines.goForw();
switch(pos_actual)
{
case 0:
ejeY++;
break;
case 1:
ejeY--;
break;
case 2:
ejeX--;
break;
default:// Si vale 3
ejeX++;
break;
}
}
void loop()
{
//establecerPrioridades(int(control[0])); //Este casting no es tal cual
//****************** TESTS ********************************
int batteryLevel = battery.testLevel();
if(batteryLevel == 0)
led.green();
else if(batteryLevel == 1)
led.yellow();
else if(batteryLevel == 2)
led.red();
else
led.no_color();
//****************** CONTROL DEL ENTORNO ********************************
observar();
//****************** ASIGNACIÓN DE VALORES A LA MATRIZ ********************************
switch(pos_actual)
{
case 0:
maze[ejeX][ejeY][1]=5; //En la opuesta a donde estamos mirando ponemos el 5
vector_valores[0]=maze[ejeX][ejeY][0];
vector_valores[2]=maze[ejeX][ejeY][2];
vector_valores[3]=maze[ejeX][ejeY][3];
break;
case 1:
vector_valores[0]=5;
vector_valores[2]=maze[ejeX][ejeY][2];
vector_valores[3]=maze[ejeX][ejeY][3];
vector_valores[1]=maze[ejeX][ejeY][1];
break;
case 2:
vector_valores[3]=5;
vector_valores[2]=maze[ejeX][ejeY][2];
vector_valores[1]=maze[ejeX][ejeY][1];
vector_valores[0]=maze[ejeX][ejeY][0];
break;
default: //Realmente sería case 3
vector_valores[2]=5;
vector_valores[3]=maze[ejeX][ejeY][3];
vector_valores[1]=maze[ejeX][ejeY][1];
vector_valores[0]=maze[ejeX][ejeY][0];
break;
}
//****************** DECISIÓN DEL CAMINO ********************************
pos_siguiente=decide_camino();
//******************** PIVOTE *******************************************
if(pos_actual != pos_siguiente)
pivotar();
avanzar();
// engines.goForw(); //hacia delante.
mybluetooth.sendMaze(ejeX,ejeY);
delay(2000);
}
/*void winCondition()
{
while(true){}
}*/
/* Podemos hacer esto en el main, ya que implica un cambio de contexto para 2 asignaciones.
void casillaInicial(String casilla,ejeX,ejeY)
{
ejeX = casilla[0];
ejeY = casilla[1];
}
*/
| true |
ecf4603bcb8fd9ac2da84b8296669cd74d9e2cf2 | C++ | TrueFinch/Figures-intersections | /tests.cpp | UTF-8 | 12,442 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "catch.hpp"
#include "figures.h"
using namespace std;
using namespace figures;
TEST_CASE("Point's tests", "[]") {
SECTION("Operator <") {
Point p1 = {1.0, 1.0}, p2 = {42.0, 42.0}, p3 = {23.08, 1999.0};
REQUIRE(p1 < p2);
REQUIRE(p1 < p3);
REQUIRE(!(p2 < p3));
REQUIRE(!(p2 < p1));
REQUIRE(!(p3 < p1));
REQUIRE(!(p3 < p2));
}
SECTION("Operator ==") {
Point p1(1.0, 1.0), p2(1.0, 1.0), p3(2.0, 1.0);
REQUIRE(p1 == p2);
REQUIRE(!(p1 == p3));
REQUIRE(!(p2 == p3));
}
}
TEST_CASE("Segment's tests", "[]") {
SECTION("Getters&Setters") {
Segment s1;
Point A(42.0, 42.0), B(9.11, 5);
vector<double> exp_params{37, -32.89, -172.62};
s1.setA(A);
s1.setB(B);
vector<double> params = s1.getParameters();
for (int i = 0; i < params.size(); ++i) {
REQUIRE(params[i] == exp_params[i]);
}
}
SECTION("Length") {
Segment s1(Point(-12.0, 0.0), Point(12.0, 0.0)), s2(Point(0.0, 0.0), Point(0.0, 0.0));
double exp_len1 = 24, exp_len2 = 0;
REQUIRE(s1.length() == exp_len1);
REQUIRE(s2.length() == exp_len2);
}
SECTION("Belong") {
Segment segment(7.0, 3.0, 13.0, 3.0);
vector<Point> belong_points{Point(7.0, 3.0), Point(13.0, 3.0), Point(10.0, 3.0)};
vector<Point> not_belong_points{Point(0.0, 0.0), Point(200.0, 200.0), Point(6.0, 3.0), Point(20.0, 3.0)};
for (auto point : belong_points) {
REQUIRE(segment.belong(point));
}
for (auto point : not_belong_points) {
REQUIRE(!segment.belong(point));
}
}
SECTION("Segment segment intersection 1") {
Segment s1(Point(0.0, 0.0), Point(2.0, 2.0)), s2(Point(0.0, 2.0), Point(2.0, 0.0));
Point exp_p(1.0, 1.0);
int exp_vec_size = 1;
vector<Point> res = s1.intersect(s2);
REQUIRE(exp_vec_size == res.size());
REQUIRE(res[0] == exp_p);
}
SECTION("Segment segment intersection 2") {
Segment s1(Point(6.0, 1.0), Point(6.0, 5.0)), s2(Point(6.0, 3.0), Point(6.0, 7.0));
vector<Point> exp_points{Point(6.0, 5.0), Point(6.0, 3.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res = s1.intersect(s2);
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Segment segment intersection 3") {
Segment s1(Point(2.0, -2.0), Point(4.0, 0.0)), s2(Point(2.0, -3.0), Point(4.0, -3.0));
int exp_vec_size = 0;
vector<Point> res = s1.intersect(s2);
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment segment intersection 4") {
Segment s1(Point(-3.0, 1.0), Point(-3.0, 3.0)), s2(Point(-4.0, 3.0), Point(-4.0, 5.0));
int exp_vec_size = 0;
vector<Point> res = s1.intersect(s2);
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment segment intersection 4") {
Segment s1(Point(-3.0, 1.0), Point(-3.0, 3.0)), s2(Point(-4.0, 3.0), Point(-4.0, 5.0));
int exp_vec_size = 0;
vector<Point> res = s1.intersect(s2);
REQUIRE(res.size() == exp_vec_size);
}
Circle circle(Point(3.0, 3.0), 3.0);
SECTION("Segment circle intersection 1") {
Segment segment(1.0, -2.0, 8.0, 5.0);
vector<Point> exp_points{Point(3.0, 0.0), Point(6.0, 3.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Segment circle intersection 2") {
Segment segment(4.0, -2.0, 7.0, -2.0);
int exp_vec_size = 0;
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment circle intersection 3") {
Segment segment(3.0, -2.0, 3.0, -4.0);
int exp_vec_size = 0;
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment circle intersection 4") {
Segment segment(-4.0, 3.0, -2.0, 3.0);
int exp_vec_size = 0;
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment circle intersection 5") {
Segment segment(-2.0, 6.0, 3.0, 6.0);
vector<Point> exp_points{Point(3.0, 6.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Segment circle intersection 6") {
Segment segment(2.0, 2.0, 4.0, 3.0);
int exp_vec_size = 0;
vector<Point> res(segment.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
}
Polyline polyline(vector<Point>{Point(-6, 1), Point(-4, 3), Point(-3, 2), Point(-1, 4), Point(0, 2)});
SECTION("Segment polyline intersection 1") {
Segment segment(1.0, 3.0, 3.0, 3.0);
double exp_vec_size = 0;
vector<Point> res(segment.intersect(polyline));
REQUIRE(res.size() == exp_vec_size);
}
SECTION("Segment polyline intersection 2") {
Segment segment(-7.0, 2.0, 3.0, 2.0);
vector<Point> exp_points{Point(-5.0, 2.0), Point(-3.0, 2.0), Point(0.0, 2.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(segment.intersect(polyline));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Segment polyline intersection 3") {
Segment segment(-3.0, -2.0, -1.0, 0.0);
double exp_vec_size = 0;
vector<Point> res(segment.intersect(polyline));
REQUIRE(res.size() == exp_vec_size);
}
}
TEST_CASE("Circle's tests", "[]") {
SECTION("Getters&Setters") {
Circle circle;
circle.setCenter(Point(1.0, 1.0));
circle.setRadius(42.0);
Point exp_point(1.0, 1.0);
REQUIRE(circle.getCenter() == exp_point);
double exp_r = 42.0;
REQUIRE(circle.getRadius() == exp_r);
}
SECTION("Length") {
Circle circle(Point(123.0, 123.0), 42.0);
double exp_len = 2 * M_PI * 42.0;
REQUIRE(circle.length() == exp_len);
}
SECTION("Belong") {
Circle circle(Point(-1.0, 4.0), 3.0);
vector<Point> belong_points{Point(-1.0, 7.0), Point(-4.0, 4.0), Point(2.0, 4.0), Point(-1.0, 1.0)};
vector<Point> not_belong_points{Point(-1.0, 4.0), Point(0.0, 0.0), Point(9.0, 5.0), Point(18.0, 8.0)};
for (auto point : belong_points) {
REQUIRE(circle.belong(point));
}
for (auto point : not_belong_points) {
REQUIRE(!circle.belong(point));
}
}
SECTION("Circle circle intersection 1") {
Circle c1(Point(-3.0, 0.0), 3.0), c2(Point(0.0, 3.0), 3.0);
vector<Point> exp_points{Point(-3.0, 3.0), Point(0.0, 0.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(c1.intersect(c2));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Circle circle intersection 2") {
Circle c1(Point(0.0, 3.0), 3.0), c2(Point(6.0, 3.0), 3.0);
vector<Point> exp_points{Point(3.0, 3.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(c1.intersect(c2));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Circle circle intersection 3") {
Circle c1(Point(-3.0, 0.0), 3.0), c2(Point(6.0, 3.0), 3.0);
int exp_vec_size = 0;
vector<Point> res(c1.intersect(c2));
REQUIRE(res.size() == exp_vec_size);
}
Circle circle(Point(-1.0, 4.0), 3.0);
SECTION("Circle polyline intersection 1") {
Polyline polyline(vector<Point>{Point(-5.0, 4.0), Point(-3.0, 4.0), Point(-1.0, 6.0),
Point(-1.0, 8.0), Point(2.0, 8.0), Point(2.0, 2.0),
Point(-1.0, -1.0), Point(-1.0, 2.0)});
vector<Point> exp_points{Point(-4.0, 4.0), Point(-1, 7.0), Point(2.0, 4.0), Point(-1.0, 1.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(circle.intersect(polyline));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
}
TEST_CASE("Polyline's tests", "[]") {
SECTION("Getter") {
Polyline polyline(vector<Point>{Point(-4.0, 0.0), Point(-2.0, 2.0), Point(0.0, 0.0), Point(2.0, 2.0),
Point(4.0, 0.0), Point(2.0, -2.0), Point(-2.0, -2.0), Point(-4.0, 0.0)});
vector<Point> exp_points{Point(-4.0, 0.0), Point(-2.0, 2.0), Point(0.0, 0.0), Point(2.0, 2.0),
Point(4.0, 0.0), Point(2.0, -2.0), Point(-2.0, -2.0), Point(-4.0, 0.0)};
vector<Point> points(polyline.getPoints());
for (auto i = 0; i < exp_points.size(); ++i) {
REQUIRE(points[i] == exp_points[i]);
}
}
SECTION("Length") {
Polyline polyline(vector<Point>{Point(0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0), Point(1.0, 0.0), Point(0.0, 0.0)});
double exp_length = 4.0;
REQUIRE(polyline.length() == exp_length);
}
SECTION("Belong") {
Polyline polyline(vector<Point>{Point(0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0), Point(1.0, 0.0), Point(0.0, 0.0)});
vector<Point> belong_points{Point(0.0, 0.5), Point(0.5, 1.0), Point(1.0, 0.5), Point(0.5, 0.0)};
vector<Point> not_belong_points{Point(0.5, 0.5), Point(2.0, 1.0), Point(0.9, 0.5), Point(0.5, -0.1)};
for (auto point : belong_points) {
REQUIRE(polyline.belong(point));
}
for (auto point : not_belong_points) {
REQUIRE(!polyline.belong(point));
}
}
SECTION("Polyline segment intersection 1") {
Segment segment(0.0, 0.0, 2.0, 2.0);
Polyline polyline(vector<Point>{Point(0.0, 4.0), Point(4.0, 0.0), Point(4.0, 2.0), Point(0.0, 2.0)});
vector<Point> exp_points{Point(2.0, 2.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(polyline.intersect(segment));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Polyline circle intersection 1") {
Circle circle(Point(0.0, 0.0), 4.0);
Polyline polyline(vector<Point>{Point(-4.0, 4.0), Point(4.0, 4.0), Point(0.0, 8.0), Point(0.0, 0.0)});
vector<Point> exp_points{Point(0.0, 4.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(polyline.intersect(circle));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
SECTION("Polyline polyline intersection 1") {
Polyline p1(vector<Point>{Point(-4.0, 0.0), Point(-2.0, 2.0), Point(0.0, 0.0), Point(2.0, 2.0),
Point(4.0, 0.0), Point(2.0, -2.0), Point(-2.0, -2.0), Point(-4.0, 0.0)}),
p2(vector<Point>{Point(-2.0, 1.0), Point(-2.0, 40), Point(2.0, 4.0), Point(2.0, 1.0), Point(0.0, -1.0)});
vector<Point> exp_points{Point(-2.0, 2.0), Point(2.0, 2.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(p1.intersect(p2));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
}
}
TEST_CASE("Other's tests", "[]") {
vector<shared_ptr<Figure>> figures;
figures.emplace_back((Figure*) new Segment(-1.0, 6.0, -1.0, 8.0)); //make_shared<Figure>(Segment(-1.0, 6.0, -1.0, 8.0))
figures.emplace_back((Figure*) new Circle(Point(-1.0, 4.0), 3.0));
figures.emplace_back((Figure*) new Polyline({Point(-1.0, 1.0), Point(-1.0, 7.0), Point(-4.0, 4.0), Point(2.0, 4.0)}));
vector<Point> exp_points{Point(-1.0, 7.0)};
auto exp_vec_size = (int) exp_points.size();
vector<Point> res(figures[0]->intersect(*figures[1]));
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
res = figures[1]->intersect(*figures[0]);
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
exp_points.clear();
exp_points.emplace_back(-1.0, 7.0);
exp_points.emplace_back(Point(-1.0, 1.0));
exp_points.emplace_back(Point(-4.0, 4.0));
exp_points.emplace_back(Point(2.0, 4.0));
exp_vec_size = (int) exp_points.size();
res = figures[2]->intersect(*figures[1]);
REQUIRE(res.size() == exp_vec_size);
for (int i = 0; i < exp_vec_size; ++i) {
REQUIRE(res[i] == exp_points[i]);
}
} | true |
4a4be5e216396ff6aac1f5fc8f76a7201ccae14e | C++ | jdibling/euler_cpp | /euler-3.0.cpp | UTF-8 | 531 | 3.265625 | 3 | [] | no_license | /*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
#include "euler.h"
void Euler_3_0()
{
//int N = 13195;
int64_t N = 600851475143;
int64_t Na = static_cast<int>(ceil(sqrt(static_cast<float>(N))));
vector<int64_t> factors;
for( int i = 2; i < Na; ++i )
{
if( !(N%i) )
factors.push_back(i);
}
vector<int64_t>::const_reverse_iterator highest_prime = find_if(factors.rbegin(), factors.rend(), &::is_prime<int>);
cout << *highest_prime << endl;
} | true |
40bcbe61edc3a34ebdbedf25bb63f05b2317bc37 | C++ | padjal/computerSystemsArchitecture | /Homework/hw1-Animals/beast.cpp | UTF-8 | 1,335 | 3.546875 | 4 | [
"MIT"
] | permissive | /**
* beast.cpp - contains functions for working with beast
*/
#include <cstring>
#include "beast.h"
#include "rnd.h"
// Enter beast parameters form file
void in(beast &be, FILE *file){
int type;
fscanf(file,"%s", be.name);
fscanf(file,"%i", &be.weight);
fscanf(file,"%i", &type);
if(type == 0){
be.type = beast::CARNIVORE;
}else if(type == 1){
be.type = beast::HERBIVORE;
}else if(type == 2){
be.type = beast::OMNIVORE;
}
}
// Enter random parameters for beast
void inRnd(beast &be){
be.type = randomInt(3) % 3;
be.weight = randomInt(2000);
strcpy(be.name, "BeastName");
}
// Output fish parameters In a formatable stream
void out(beast &be, FILE *file){
char* type;
switch (be.type) {
case 0:
type = "carnivore";
break;
case 1:
type = "herbivore";
break;
case 2:
type = "omnivore";
break;
}
fprintf(file, "It is a Beast: name = %s, weight: %i, is: %s, and has a special number: %f\n",
be.name, be.weight, type, specialNumber(be));
}
double specialNumber(beast &be){
double charSum = 0;
for (int i = 0 ; i < sizeof(be.name) / sizeof(be.name[0]) ; ++i) {
charSum += be.name[i];
}
return charSum / be.weight;
} | true |
cb055769902dbefc52877dff0156dc73760f07a5 | C++ | seth1002/antivirus-1 | /CommonFiles/Licensing2/src/Verdict.h | UTF-8 | 1,225 | 3.03125 | 3 | [] | no_license | /**
* @file
* @brief Implementaion of IVerdict interface.
* @author Andrey Guzhov
* @date 12.07.2005
* @version 1.0
*/
#ifndef VERDICT_H
#define VERDICT_H
#include <vector>
namespace KasperskyLicensing {
namespace Implementation {
/**
* Implements IVerdict interface.
*/
class Verdict : public IVerdict
{
public:
/**
* Constructs verdict object by given verdict value.
* @param[in] value verdict value.
*/
explicit Verdict(bool value);
/**
* Constructs verdict object by given verdict value and notification id.
* @param[in] value verdict value.
* @param[in] notif_id notification identifier.
*/
Verdict(bool value, unsigned notif_id);
/**
* Returns true if corresponding license restriction is satisfied.
*/
virtual bool IsPositive() const;
/**
* Returns notification enumerator.
*/
virtual NotificationEnumerator GetNotifications() const;
/**
* Adds notification identifier.
*/
void AddNotification(unsigned id);
private:
// verdict value
bool verdict_value;
// notifications list
std::vector<unsigned> notif_list;
};
} // namespace Implementation
} // namespace KasperskyLicensing
#endif // VERDICT_H
| true |
2028a12f5bfb8300dc776cbb59faa343c0332d9a | C++ | WarcramSpartanix/GD-ENG-MO | /DirectXGame/CameraManager.cpp | UTF-8 | 4,445 | 2.859375 | 3 | [] | no_license | #include "CameraManager.h"
#include "EngineTime.h"
#include "InputSystem.h"
CameraManager* CameraManager::sharedInstance = nullptr;
CameraManager* CameraManager::getInstance()
{
if (sharedInstance == nullptr)
initialize();
return sharedInstance;
}
void CameraManager::initialize()
{
sharedInstance = new CameraManager();
}
void CameraManager::destroy()
{
sharedInstance->m_active_camera = nullptr;
delete sharedInstance->m_game_camera;
delete sharedInstance->m_scene_camera;
}
Camera* CameraManager::getSceneCamera()
{
return nullptr;
}
Camera** CameraManager::getActiveCameraAddress()
{
return &m_active_camera;
}
GameCamera* CameraManager::getGameCam()
{
return m_game_camera;
}
void CameraManager::setGameCamera(GameCamera* gameCamera)
{
m_game_camera = gameCamera;
}
void CameraManager::setActiveCamera(CameraType type)
{
switch (type)
{
case CameraManager::SCENE_CAMERA:
if(m_active_camera == m_game_camera)
{
m_active_camera = m_scene_camera;
InputSystem::getInstance()->addListener(m_scene_camera);
InputSystem::getInstance()->removeListener(m_game_camera);
}
break;
case CameraManager::GAME_CAMERA:
if (m_active_camera == m_scene_camera && m_game_camera != nullptr)
{
m_active_camera = m_game_camera;
InputSystem::getInstance()->addListener(m_game_camera);
InputSystem::getInstance()->removeListener(m_scene_camera);
}
break;
default:
break;
}
}
void CameraManager::switchCamera()
{
m_camera_toggle = !m_camera_toggle;
}
void CameraManager::update()
{
if (m_scene_camera != nullptr)
m_scene_camera->update(EngineTime::getDeltaTime());
if (m_game_camera != nullptr)
m_game_camera->update(EngineTime::getDeltaTime());
if (m_camera_toggle)
{
if (m_active_camera == m_scene_camera && m_game_camera != nullptr)
{
m_active_camera = m_game_camera;
InputSystem::getInstance()->addListener(m_game_camera);
InputSystem::getInstance()->removeListener(m_scene_camera);
}
else
{
m_active_camera = m_scene_camera;
InputSystem::getInstance()->addListener(m_scene_camera);
InputSystem::getInstance()->removeListener(m_game_camera);
}
m_camera_toggle = false;
}
//align with view
bool ctrl = InputSystem::getInstance()->isKeyDown(16);
bool shift = InputSystem::getInstance()->isKeyDown(17);
bool F = InputSystem::getInstance()->isKeyDown(70);
if (ctrl && shift && F)
{
m_align_animating = true;
}
if (m_game_camera != nullptr && m_align_animating == true)
{
if (m_align_percent < 1.0f)
{
m_align_percent += EngineTime::getDeltaTime();
m_game_camera->setPosition(Vector3D::lerp(m_game_camera->getLocalPosition(), m_scene_camera->getLocalPosition(), m_align_percent));
m_game_camera->setRotation(Vector3D::lerp(m_game_camera->getLocalRotation(), m_scene_camera->getLocalRotation(), m_align_percent));
}
else
{
m_align_percent = 0.0f;
m_align_animating = false;
}
}
else
m_align_animating = false; // in case game camera not yet created. Avoid issues
}
void CameraManager::drawGameCamera(ConstantBuffer* cb)
{
if(m_game_camera != nullptr)
m_game_camera->draw(cb);
}
Matrix4x4 CameraManager::getCameraViewMatrix()
{
return m_scene_camera->getViewMatrix();
}
std::vector<Matrix4x4> CameraManager::getAllCameraViewMatrices()
{
std::vector<Matrix4x4> out;
out.push_back(m_scene_camera->getViewMatrix());
if (m_game_camera != nullptr)
out.push_back(m_game_camera->getViewMatrix());
return out;
}
void CameraManager::alignView()
{
m_align_animating = true;
}
void CameraManager::onKeyDown(int key)
{
}
void CameraManager::onKeyUp(int key)
{
if (key == 'T')//tab
{
m_camera_toggle = !m_camera_toggle;
}
}
void CameraManager::onMouseMove(const Point& delta_mouse_pos)
{
}
void CameraManager::onLeftMouseDown(const Point& mouse_pos)
{
}
void CameraManager::onLeftMouseUp(const Point& mouse_pos)
{
}
void CameraManager::onRightMouseDown(const Point& mouse_pos)
{
}
void CameraManager::onRightMouseUp(const Point& mouse_pos)
{
}
CameraManager::CameraManager()
{
InputSystem::getInstance()->addListener(this);
m_scene_camera = new Camera("SceneCamera");
InputSystem::getInstance()->addListener(m_scene_camera);
/*m_game_camera = new GameCamera("GameCamera", Vector3D(0, 0, -2));
InputSystem::getInstance()->removeListener(m_game_camera);*/
m_active_camera = m_scene_camera;
m_scene_camera->setPosition(0, 0, -2);
}
CameraManager::~CameraManager()
{
} | true |
e6cd9cf578c46815d9dd0da265aa4bdea55f667f | C++ | Elojah/Meuh2.0 | /util/Rool/src/MemberTemplate.cpp | UTF-8 | 969 | 2.625 | 3 | [] | no_license | #include "MemberTemplate.hpp"
#include "ReplaceClassName.hpp"
#include <fstream>
#include <string.h>
MemberTemplate::MemberTemplate(void) {
}
MemberTemplate::MemberTemplate(std::string const &path) : _path(path) {
}
MemberTemplate::~MemberTemplate(void) {
for (tBehaviors::const_iterator it = _behav.begin(); it != _behav.end(); ++it) {
delete (*it);
}
}
std::string MemberTemplate::create(const std::string &str) {
if (str.empty()) {
return ("Nothing done");
}
for (tBehaviors::const_iterator it = _behav.begin(); it != _behav.end(); ++it) {
if ((*it)->isBehavior(str)) {
(*it)->init(str, _path);
return ((*it)->makeBehavior());
}
}
return ("No behavior matched with entry ...");
}
std::vector<TemplateBehavior *> MemberTemplate::createBehavMap(void) {
tBehaviors result;
result.push_back(new ReplaceClassName);
return (result);
}
const std::vector<TemplateBehavior *> MemberTemplate::_behav = MemberTemplate::createBehavMap();
| true |
180433ad8495392d0d9686a8e9959ebd7ceb4716 | C++ | conquerheaven/EnergyMonitor | /code/cal.cpp | UTF-8 | 1,321 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
struct point{
double x , y;
point(double x , double y):x(x),y(y){}
};
vector<point> pv , allp;
vector<point> result;
double L(double x){
double sum = 0;
for(int i = 0; i < pv.size(); i++){
double li = 1.0;
for(int j = 0; j < pv.size(); j++){
if(i == j) continue;
li = li*(x - pv[j].x)/(pv[i].x - pv[j].x);
}
sum += pv[i].y * li;
}
return sum;
}
void computing(){
for(int i = 502; i <= 527; i++){
result.push_back(point(i , L(i)));
}
int cnt = 0;
for(int i = 0; i < allp.size(); i++){
cout << allp[i].x << " " << allp[i].y << endl;
if(i != 0){
for(int j = allp[i].x+1; j < allp[i-1].x; j++){
cout << j << " " << 0 << endl;
}
}
}
for(int i = 0; i < result.size(); i++){
cout << result[i].x << " " << result[i].y << endl;
}
}
int main(){
freopen("in.txt" , "r" , stdin);
freopen("out.txt" , "w" , stdout);
double x , y;
int C = 0;
while(cin >> x >> y){
if(C == 0) pv.push_back(point(x , y));
C = (C+1)%20;
allp.push_back(point(x, y));
}
computing();
return 0;
}
| true |
7a179f3d7d4fadbe73df6947d5f78c436bfe0bf0 | C++ | blackHatMonkey/maze_runner | /disjointset_test.cpp | UTF-8 | 14,759 | 3.03125 | 3 | [] | no_license | /*
* To compile: g++ disjointset.cpp disjointset_test.cpp timer.cpp -std=c++0x
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include "disjointset.hpp"
#include "timer.hpp"
bool test1(std::string &error);
bool test2(std::string &error);
bool test3(std::string &error);
bool test4(std::string &error);
bool test5(std::string &error);
bool test6(std::string &error);
bool test7(std::string &error);
bool test8(std::string &error);
bool test9(std::string &error);
bool test10(std::string &error);
bool test11(std::string &error);
const int numTests = 11;
typedef bool (*TestPtr)(std::string &);
int main(void) {
TestPtr runTest[numTests] = {test1, test2, test3, test4, test5, test6,
test7, test8, test9, test10, test11};
std::string msg;
bool result = true;
int numPassed = 0;
for (int i = 0; result && i < numTests; i++) {
result = runTest[i](msg);
if (!result) {
std::cout << msg << std::endl;
} else {
numPassed++;
std::cout << "Test " << i + 1 << " passed!" << std::endl;
}
}
if (numPassed == numTests) {
std::cout << "All tests passed!" << std::endl;
return 0;
} else {
std::cout << "Tests failing!" << std::endl;
return 1;
}
}
/* test1: make 100 disjoint sets, check return value. Call makeSet() on
sets that are made, ensure that return is false.
*/
bool test1(std::string &error) {
DisjointSet theSet(100);
bool result;
bool rc = true;
for (int i = 0; rc && i < 100; i++) {
result = theSet.makeSet(i);
if (!result) {
rc = false;
error = "Error 1a: makeSet() return value error, function should have "
"returned true";
}
}
for (int i = 0; rc && i < 100; i++) {
result = theSet.makeSet(i);
if (result) {
rc = false;
error = "Error 1b: makeSet() return value error, function should have "
"returned false";
}
}
return rc;
}
/*test2: call findSet() on sets with 1 item, it should be rep*/
bool test2(std::string &error) {
DisjointSet theSet(100);
int result;
bool rc = true;
for (int i = 0; rc && i < 100; i++) {
theSet.makeSet(i);
result = theSet.findSet(i);
if (result != i) {
rc = false;
error = "Error 2: findSet() did not return the correct representative";
}
}
return rc;
}
/*test3: create 100 items, merge together into pairs, check
that their representatives are consistent*/
bool test3(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
if (result != true) {
rc = false;
error = "Error 3: unionSets() did not return the correct value, it "
"should have returned true";
}
}
for (int i = 0; rc && i < 50; i++) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet(i * 2 + 1);
if (rep1 != rep2) {
rc = false;
error = "Error 3: findSet() is returning two different reps for objects "
"in same set";
}
if (rc && (rep1 != i * 2 && rep1 != (i * 2 + 1))) {
rc = false;
error = "Error 3: findSet() is returning a value that is not a member of "
"the set";
}
}
return rc;
}
/*test 4: try to call unionSets() with values that are not the reps
for the set, check return value, ensure that union() did not occur*/
bool test4(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
int arg1 = (rep1 == i * 2) ? i * 2 + 1 : i * 2;
int arg2 = (rep2 == (i + 1) * 2) ? (i + 1) * 2 + 1 : (i + 1) * 2;
result = theSet.unionSets(arg1, arg2);
if (result != false) {
rc = false;
error = "Error 4: unionSets() should return false if non-representatives "
"are used as arguments";
} else {
if (theSet.findSet(arg1) == theSet.findSet(arg2)) {
rc = false;
error = "Error 4: uninonSet() should have done nothing if "
"non-representatives were used as arguments";
}
}
}
return rc;
}
/*test 5: unionSets() on sets that are more than 1 element big*/
bool test5(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
result = theSet.unionSets(rep1, rep2);
if (result == false) {
rc = false;
error = "Error 5a: unionSets() returned false, it should have returned "
"true as sets should have been unioned";
} else {
if (theSet.findSet(rep1) != theSet.findSet(rep2)) {
rc = false;
error = "Error 5b: uninonSet() should have combined the two sets and "
"their reps should be same";
}
}
}
return rc;
}
/*Test 6: further testing on unionSets() and findSet()*/
bool test6(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
theSet.unionSets(rep1, rep2);
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
rep1 = theSet.findSet(i);
rep2 = theSet.findSet(j);
result = theSet.unionSets(rep1, rep2);
if (result == false) {
rc = false;
error =
"Error 6a: unionSets() returned false, it should have returned true";
}
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = theSet.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (theSet.findSet(i + k) != newRep) {
rc = false;
error =
"Error 6b: findSet() did not return a consistent representative";
}
if (theSet.findSet(j - k) != newRep) {
rc = false;
error =
"Error 6c: findSet() did not return a consistent representative";
}
}
}
rep1 = theSet.findSet(97);
rep2 = theSet.findSet(50);
result = theSet.unionSets(rep1, rep2);
if (result == false) {
rc = false;
error =
"Error 6d: unionSets() returned false, it should have returned true";
}
int newRep = theSet.findSet(0);
for (int i = 0; rc && i < 4; i++) {
if (theSet.findSet(i) != newRep) {
rc = false;
error = "Error 6e: findSet() did not return a consistent representative";
}
}
for (int i = 0; rc && i < 4; i++) {
if (theSet.findSet(99 - i) != newRep) {
rc = false;
error = "Error 6f: findSet() did not return a consistent representative";
}
}
for (int i = 0; rc && i < 4; i++) {
if (theSet.findSet(i + 48) != newRep) {
rc = false;
error = "Error 6g: findSet() did not return a consistent representative";
}
}
return rc;
}
/*Test 7: Test copy constructor*/
bool test7(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
theSet.unionSets(rep1, rep2);
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
rep1 = theSet.findSet(i);
rep2 = theSet.findSet(j);
result = theSet.unionSets(rep1, rep2);
}
DisjointSet copy = theSet;
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = copy.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (copy.findSet(i + k) != newRep) {
rc = false;
error = "Error 7: Copy constructor did not produce a duplicate with "
"same disjoint sets";
}
if (copy.findSet(j - k) != newRep) {
rc = false;
error = "Error 7b: Copy constructor did not produce a duplicate with "
"same disjoint sets";
}
}
}
rep1 = theSet.findSet(97);
rep2 = theSet.findSet(50);
result = theSet.unionSets(rep1, rep2);
if (copy.findSet(97) == copy.findSet(50)) {
rc = false;
error = "Error 7c: Copy constructor appears to not have made a deep copy";
}
return rc;
}
/*Test 8: Test Assignment Operator*/
bool test8(std::string &error) {
DisjointSet theSet(100);
DisjointSet copy(50);
DisjointSet copy2(30);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 50; i++) {
copy.makeSet(i);
}
for (int i = 0; i < 30; i++) {
copy2.makeSet(i);
}
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
theSet.unionSets(rep1, rep2);
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
rep1 = theSet.findSet(i);
rep2 = theSet.findSet(j);
result = theSet.unionSets(rep1, rep2);
}
copy2 = copy = theSet;
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = copy.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (copy.findSet(i + k) != newRep) {
rc = false;
error = "Error 8a: copy assignment operator did not produce a "
"duplicate with same disjoint sets";
}
if (copy.findSet(j - k) != newRep) {
rc = false;
error = "Error 8b: copy assignment operator did not produce a "
"duplicate with same disjoint sets";
}
}
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = copy2.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (copy2.findSet(i + k) != newRep) {
rc = false;
error = "Error 8c: possible return value error in assignment operator";
}
if (copy2.findSet(j - k) != newRep) {
rc = false;
error = "Error 8d: possible return value error in assignment operator";
}
}
}
rep1 = theSet.findSet(97);
rep2 = theSet.findSet(50);
result = theSet.unionSets(rep1, rep2);
if (copy.findSet(97) == copy.findSet(50)) {
rc = false;
error =
"Error 8e: assignment operator appears to not have made a deep copy";
}
if (copy2.findSet(97) == copy2.findSet(50)) {
rc = false;
error =
"Error 8e: assignment operator appears to not have made a deep copy";
}
return rc;
}
/*Test 9: Test move constructor*/
bool test9(std::string &error) {
DisjointSet theSet(100);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
theSet.unionSets(rep1, rep2);
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
rep1 = theSet.findSet(i);
rep2 = theSet.findSet(j);
result = theSet.unionSets(rep1, rep2);
}
DisjointSet copy = std::move(theSet);
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = copy.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (copy.findSet(i + k) != newRep) {
rc = false;
error = "Error 9a: move constructor did not produce a duplicate with "
"same disjoint sets";
}
if (copy.findSet(j - k) != newRep) {
rc = false;
error = "Error 9b: move constructor did not produce a duplicate with "
"same disjoint sets";
}
}
}
return rc;
}
/*Test 10: Test Move Assignment Operator*/
bool test10(std::string &error) {
DisjointSet theSet(100);
DisjointSet copy(50);
bool result;
int rep1;
int rep2;
bool rc = true;
for (int i = 0; i < 50; i++) {
copy.makeSet(i);
}
for (int i = 0; i < 100; i++) {
theSet.makeSet(i);
}
for (int i = 0; rc && i < 100; i += 2) {
result = theSet.unionSets(i, i + 1);
}
for (int i = 0; rc && i < 50; i += 2) {
rep1 = theSet.findSet(i * 2);
rep2 = theSet.findSet((i + 1) * 2);
theSet.unionSets(rep1, rep2);
}
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
rep1 = theSet.findSet(i);
rep2 = theSet.findSet(j);
result = theSet.unionSets(rep1, rep2);
}
copy = std::move(theSet);
for (int i = 0, j = 99; rc && i < 48; i += 4, j -= 4) {
int newRep = copy.findSet(i);
for (int k = 0; rc && k < 4; k++) {
if (copy.findSet(i + k) != newRep) {
rc = false;
error = "Error 10a: move assignment did not produce a duplicate with "
"same disjoint sets";
}
if (copy.findSet(j - k) != newRep) {
rc = false;
error = "Error 10b: move assignment did not produce a duplicate with "
"same disjoint sets";
}
}
}
return rc;
}
/*Test 11: Timing runs, no errors for these.*/
bool test11(std::string &error) {
Timer t;
Timer t2;
DisjointSet set1(50000);
DisjointSet set2(50000);
t.reset();
for (int i = 0; i < 50000; i++) {
t.start();
set1.makeSet(i);
set2.makeSet(i);
t.stop();
}
std::cout << "100000 makeSet(): " << t.currtime() << std::endl;
int rep1;
int rep2;
t.reset();
t2.reset();
for (int i = 0; i < 49999; i++) {
t.start();
rep1 = set1.findSet(i);
rep2 = set1.findSet(i + 1);
t.stop();
t2.start();
set1.unionSets(rep1, rep2);
t2.stop();
}
std::cout << "49998 findSet(): " << t.currtime() << std::endl;
std::cout << "49999 unionSets(): " << t2.currtime() << std::endl;
t.reset();
t2.reset();
for (int i = 0; i < 49999; i++) {
int choice = rand() % (i + 1);
t.start();
rep1 = set1.findSet(choice);
rep2 = set1.findSet(i + 1);
t.stop();
t2.start();
set1.unionSets(rep2, rep1);
t2.stop();
}
std::cout << "another 49998 findSet(): " << t.currtime() << std::endl;
std::cout << "another 49999 unionSets(): " << t2.currtime() << std::endl;
return true;
} | true |
00ab7b3b5126fdf273e2773422a93c48ff36af1c | C++ | chenyangfan13/LearnRoboticsCpp | /include/path_planning/rrtbase.hpp | UTF-8 | 1,358 | 2.609375 | 3 | [] | no_license | #pragma once
struct Node {
float x;
float y;
std::vector<float> path_x;
std::vector<float> path_y;
int parent = -1;
int idx = -1; // position in nodes_list_
float cost = 0.0f;
Node (float _x, float _y) : x(_x), y (_y) {}
Node () {}
};
using CircleObstacle = std::tuple<float, float, float>;
class RRTBase {
public:
virtual std::pair<std::vector<float>, std::vector<float>>
plan(float sx, float sy, float gx, float gy) = 0;
protected:
Node generateRandomNode();
size_t nearestNodeIndex(Node& query);
// returns new node who's parent is from_node
Node steer(Node& from_node, Node& to_node, float extend_length=std::numeric_limits<float>::infinity());
bool noCollision(Node& n);
std::pair<std::vector<float>, std::vector<float>>
generateFinalCourse(int goal_ind);
std::pair<float, float> calculateDistanceAndAngle(Node& s, Node& g);
float calculateDistanceToGoal(Node& n);
int searchBestGoalNode();
std::vector<Node> nodes_list_;
std::vector<CircleObstacle> obs_;
float min_rand_;
float max_rand_;
float expand_dis_;
float path_res_;
float goal_sample_rate_;
size_t max_iter_;
// float connect_circle_dist_;
Node goal_node_;
Node start_node_;
};
class RRT : public RRTBase {
public:
};
| true |
9bb290ce6c1f44196c6569acc92d1e4034863b4b | C++ | jonathanpoelen/falcon | /falcon/functional/invoke_partial_recursive_param_loop.hpp | UTF-8 | 2,455 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP
#define FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP
#include <falcon/math/min.hpp>
#include <falcon/c++1x/syntax.hpp>
#include <falcon/functional/invoke.hpp>
#include <falcon/parameter/manip.hpp>
#include <falcon/preprocessor/not_ide_parser.hpp>
#include <utility>
namespace falcon {
template<std::size_t NumberArg>
class invoke_partial_recursive_param_loop_fn
{
static_assert(NumberArg > 1, "NumberArg < 2");
template<std::size_t N, class = void>
struct Impl {
template<
class F, class... Args
, std::size_t Start = (N - 1) * (NumberArg - 1) + NumberArg + 1>
static constexpr CPP1X_DELEGATE_FUNCTION(
impl_(F && func, Args&&... args)
, invoke(
typename parameter_index_cat<
parameter_index<0>,
build_range_parameter_index_t<
Start
, min(Start + (NumberArg - 1), sizeof...(Args) + 1)
>
>::type()
, std::forward<F>(func)
, Impl<N-1>::impl_(std::forward<F>(func), std::forward<Args>(args)...)
, std::forward<Args>(args)...
)
)
};
template<class T>
struct Impl<0, T> {
template<class F, class... Args>
static constexpr CPP1X_DELEGATE_FUNCTION(
impl_(F && func, Args&&... args)
, invoke(
build_parameter_index_t<min(NumberArg, sizeof...(Args))>()
, std::forward<F>(func)
, std::forward<Args>(args)...
)
)
};
public:
constexpr invoke_partial_recursive_param_loop_fn() noexcept {}
template<
class F, class... Args
, std::size_t N = (sizeof...(Args) - 2) / (NumberArg - 1)>
constexpr CPP1X_DELEGATE_FUNCTION(
operator()(F && func, Args&&... args) const
, Impl<N>::impl_(std::forward<F>(func), std::forward<Args>(args)...)
)
};
/**
* \brief Call \c func with \c NumberArg arguments. The return of \c func is the first argument of next call.
* \return Last operations.
*
* \code
* int n = invoke_partial_param_loop<2>(accu_t(), 1,2,3,4,5,6);
* \endcode
* equivalent to
* \code
* accu_t accu;
* int n = accu(accu(accu(accu(accu(1,2),3),4),5),6);
* \endcode
*
* \ingroup call-arguments
*/
template<std::size_t NumberArg, class F, class... Args>
constexpr CPP1X_DELEGATE_FUNCTION(
invoke_partial_recursive_param_loop(F func, Args&&... args)
, invoke_partial_recursive_param_loop_fn<NumberArg>()(
std::forward<F>(func), std::forward<Args>(args)...)
)
}
#endif
| true |
c5aa05bca1514b5510b7395a9a3d0e1e70725bbe | C++ | telwell/nand2tetris | /06/assembler/Parser.hpp | UTF-8 | 681 | 2.671875 | 3 | [] | no_license | #include <string>
#include <fstream>
class Parser
{
public:
Parser(std::string file);
void incLineNum();
// File methods
void openFile();
void closeFile();
void next();
// Getters
int getLineNum();
std::string getFileName();
// Command
std::string getCurrentCommand();
void oCurrentCommand();
bool hasMoreCommands();
std::string commandType();
// Symbol
std::string symbol();
bool isInt( std::string &in );
int toInt( std::string &in );
// Dest
std::string dest();
// Comp
std::string comp();
// Jump
std::string jump();
private:
int lineNum;
std::string filename;
std::ifstream ifs;
std::string current_command;
};
| true |
1769c50c98dfad7f71a61c41a9c8cc3103531660 | C++ | khalilovske/IT-STEP | /Class works/9.4.2019 Files,Tasks/9.4.2019 Files,Tasks/Fill.cpp | UTF-8 | 191 | 2.59375 | 3 | [] | no_license | #include"Arrays.h"
#include<ctime>
#include<iostream>
using namespace std;
void Fill(int *const arr, int const size) {
for (int i = 0; i < size; i++) {
arr[i] = rand() % 10;
}
} | true |
c142b4de9a2feddb7bd4f8fe79186e31c7f524ed | C++ | burakkose/HackerRank | /Challenges/Code Golf/Sudoku/sudoku_solver.cpp | UTF-8 | 1,552 | 3.140625 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
#include <list>
#define N 9
using namespace std;
list<int> zeroPos;
bool isSafe(int grid[N][N],int mrow,int mcol,int num){
for(int i = 0 ; i < 9 ; i++)
if(grid[mrow][i] == num || grid[i][mcol] == num )
return false;
mrow -= (mrow%3);
mcol -= (mcol%3);
for(int i = 0 ; i < 3 ; i++)
for(int j = 0 ; j < 3 ; j++){
if(grid[i+mrow][j+mcol] == num)
return false;
}
return true;
}
bool SudokuSolve(int grid[N][N]){
if(zeroPos.empty())
return true;
int m_row = zeroPos.front() / 9;
int m_col = zeroPos.front() % 9;
for(int num = 1 ; num < 10 ; num++){
if(isSafe(grid,m_row,m_col,num)){
grid[m_row][m_col]=num;
zeroPos.pop_front();
if(SudokuSolve(grid))
return true;
grid[m_row][m_col] = 0;
zeroPos.push_front(m_row * 9 + m_col);
}
}
return false;
}
int main()
{
int n;
cin >> n;
while(n--){
int grid[N][N];
for(int i = 0 ; i < N ; i++)
for(int j = 0 ; j < N ; j++){
grid[i][j] = 0;
cin >> grid[i][j];
if(!grid[i][j])
zeroPos.push_back(i*9 + j);
}
SudokuSolve(grid);
for (int i = 0 ; i < N; i++) {
for (int j = 0 ; j < N; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
zeroPos.clear();
}
return 0;
}
| true |
7d01a53231e2dd5116846b1f5c694ecdf3b637d6 | C++ | hryuh1121/Team16 | /Project1/Model.cpp | SHIFT_JIS | 38,168 | 2.6875 | 3 | [] | no_license | #include "Model.h"
#include "DirectXTex.h"
#include<d3dx12.h>
#include "Camera.h"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#pragma warning(disable : 4996)
using namespace DirectX;
using namespace Microsoft::WRL;
using namespace std;
//ÓIoϐ̎
ID3D12Device* Model::device = nullptr;
UINT Model::descriptorHandleIncrementSize = 0;
CD3DX12_CPU_DESCRIPTOR_HANDLE Model::cpuDescHandleSRV;
CD3DX12_GPU_DESCRIPTOR_HANDLE Model::gpuDescHandleSRV;
Model::Material Model::material;
ComPtr<ID3D12DescriptorHeap> Model::descHeap;
#pragma region PMDpnamespace
namespace {
///f̃pXƃeNX`̃pX獇pX
///@param modelPath AvP[V猩pmdf̃pX
///@param texPath PMDf猩eNX`̃pX
///@return AvP[V猩eNX`̃pX
std::string GetTexturePathFromModelAndTexPath(const std::string& modelPath, const char* texPath) {
//t@C̃tH_\/̓ނgp\
//Ƃ\/̂ŁAorfindƂr
//int^ɑĂ̂͌Ȃꍇrfindepos(-10xffffffff)Ԃ
int pathIndex1 = modelPath.rfind('/');
int pathIndex2 = modelPath.rfind('\\');
auto pathIndex = max(pathIndex1, pathIndex2);
auto folderPath = modelPath.substr(0, pathIndex + 1);
return folderPath + texPath;
}
///t@Cgq擾
///@param path Ώۂ̃pX
///@return gq
string
GetExtension(const std::string& path) {
int idx = path.rfind('.');
return path.substr(idx + 1, path.length() - idx - 1);
}
///t@Cgq擾(Ch)
///@param path Ώۂ̃pX
///@return gq
wstring
GetExtension(const std::wstring& path) {
int idx = path.rfind(L'.');
return path.substr(idx + 1, path.length() - idx - 1);
}
///eNX`̃pXZp[^ŕ
///@param path Ώۂ̃pX
///@param splitter 蕶
///@return O̕yA
pair<string, string>
SplitFileName(const std::string& path, const char splitter = '*') {
int idx = path.find(splitter);
pair<string, string> ret;
ret.first = path.substr(0, idx);
ret.second = path.substr(idx + 1, path.length() - idx - 1);
return ret;
}
///string(}`oCg)wstring(Ch)
///@param str }`oCg
///@return ϊꂽCh
std::wstring
GetWideStringFromString(const std::string& str) {
//Ăяo1()
auto num1 = MultiByteToWideChar(CP_ACP,
MB_PRECOMPOSED | MB_ERR_INVALID_CHARS,
str.c_str(), -1, nullptr, 0);
std::wstring wstr;//stringwchar_t
wstr.resize(num1);//ꂽŃTCY
//Ăяo2(mۍς݂wstrɕϊRs[)
auto num2 = MultiByteToWideChar(CP_ACP,
MB_PRECOMPOSED | MB_ERR_INVALID_CHARS,
str.c_str(), -1, &wstr[0], num1);
assert(num1 == num2);//ꉞ`FbN
return wstr;
}
///fobOC[Lɂ
void EnableDebugLayer() {
ComPtr<ID3D12Debug> debugLayer = nullptr;
auto result = D3D12GetDebugInterface(IID_PPV_ARGS(&debugLayer));
debugLayer->EnableDebugLayer();
}
}
#pragma endregion
void* Model::Transform::operator new(size_t size) {
return _aligned_malloc(size, 16);
}
//void Model::RecursiveMatrixMultipy(BoneNode* node,const DirectX::XMMATRIX& mat)
//{
// _boneMatrices[node->boneIdx] = mat;
// for (auto& cnode : node->children)
// {
// RecursiveMatrixMultipy(cnode, _boneMatrices[cnode->boneIdx] * mat);
// }
//}
void Model::StaticInitialize(ID3D12Device * device)
{
Model::device = device;
// fXNv^TCY擾
descriptorHandleIncrementSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
void Model::CreateModel(UINT texNumber, const std::string& modelname)
{
this->modeldata = OBJ;
//t@CXg[
std::ifstream file;
//.objt@CJ
//file.open("Resources/triangle/triangle_tex.obj");
//const string modelname = "skydome";
const string filename = modelname + ".obj";//"triangle_mat.obj"
const string directoryPath = "Resources/" + modelname + "/";//"Resources/triangle_mat/"
file.open(directoryPath + filename);//"Resource/triangle_mat/triangle_mat.obj"
//t@CI[vs`FbN
if (file.fail()) {
assert(0);
}
vector<XMFLOAT3>positions;//_W
vector<XMFLOAT3>normals;//@׃Ng
vector<XMFLOAT2>texcoords;//eNX`UV
//1sǂݍ
string line;
while (getline(file, line)) {
//1s̕Xg[ɕϊĉ͂₷
std::istringstream line_stream(line);
//pXy[Xōs̐擪擾
string key;
getline(line_stream, key, ' ');
//擪mtllibȂ}eA
if (key == "mtllib")
{
//}eÃt@Cǂݍ
string filename;
line_stream >> filename;
//}eAǂݍ
LoadMaterial(texNumber, directoryPath, filename);
}
//擪vȂ璸_W
if (key == "v") {
//X,Y,ZWǂݍ
XMFLOAT3 position{};
line_stream >> position.x;
line_stream >> position.y;
line_stream >> position.z;
//Wf[^ɒlj
positions.emplace_back(position);
////_f[^ɒlj
//VertexPosNormalUv vertex{};
//vertex.pos = position;
//vertices.emplace_back(vertex);
}
//擪vtȂeNX`
if (key == "vt") {
//UVǂݍ
XMFLOAT2 texcoord{};
line_stream >> texcoord.x;
line_stream >> texcoord.y;
//V]
texcoord.y = 1.0f - texcoord.y;
//eNX`Wf[^ɒlj
texcoords.emplace_back(texcoord);
}
//擪vnȂ@xNg
if (key == "vn") {
//X,Y,Zǂݍ
XMFLOAT3 normal{};
line_stream >> normal.x;
line_stream >> normal.y;
line_stream >> normal.z;
//@xNgf[^
normals.emplace_back(normal);
}
//擪fȂ|S(Op`)
if (key == "f")
{
//pXy[Xōs̑ǂݍ
string index_string;
while (getline(line_stream, index_string, ' ')) {
//_CfbNX1̕Xg[ɕϊĉ͂₷
std:istringstream index_stream(index_string);
unsigned short indexPosition, indexNormal, indexTexcoord;
index_stream >> indexPosition;
index_stream.seekg(1, ios_base::cur);//XbV
index_stream >> indexTexcoord;
index_stream.seekg(1, ios_base::cur);//XbV
index_stream >> indexNormal;
//_f[^̒lj
VertexPosNormalUv vertex{};
vertex.pos = positions[indexPosition - 1];
vertex.normal = normals[indexNormal - 1];
vertex.uv = texcoords[indexTexcoord - 1];
modelvertices.emplace_back(vertex);
//CfbNXf[^̒lj
modelindices.emplace_back((unsigned short)modelindices.size());
////_CfbNXɒlj
//indices.emplace_back(indexPosition - 1);
}
}
}
file.close();
HRESULT result = S_FALSE;
UINT sizeVB = static_cast<UINT>(sizeof(VertexPosNormalUv)*modelvertices.size());
UINT sizeIB = static_cast<UINT>(sizeof(unsigned short)*modelindices.size());
// _obt@
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(sizeVB),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&vertBuff));
if (FAILED(result)) {
assert(0);
return;
}
// CfbNXobt@
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
//&CD3DX12_RESOURCE_DESC::Buffer(sizeof(indices)),
&CD3DX12_RESOURCE_DESC::Buffer(sizeIB),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&indexBuff));
if (FAILED(result)) {
assert(0);
return;
}
// _obt@ւ̃f[^]
VertexPosNormalUv* vertMap = nullptr;
result = vertBuff->Map(0, nullptr, (void**)&vertMap);
if (SUCCEEDED(result)) {
//memcpy(vertMap, vertices, sizeof(vertices));
std::copy(modelvertices.begin(), modelvertices.end(), vertMap);
vertBuff->Unmap(0, nullptr);
}
// CfbNXobt@ւ̃f[^]
unsigned short* indexMap = nullptr;
result = indexBuff->Map(0, nullptr, (void**)&indexMap);
if (SUCCEEDED(result)) {
std::copy(modelindices.begin(), modelindices.end(), indexMap);
indexBuff->Unmap(0, nullptr);
}
// _obt@r[̍쐬
vbView.BufferLocation = vertBuff->GetGPUVirtualAddress();
//vbView.SizeInBytes = sizeof(vertices);
vbView.SizeInBytes = sizeVB;
vbView.StrideInBytes = sizeof(modelvertices[0]);
// CfbNXobt@r[̍쐬
ibView.BufferLocation = indexBuff->GetGPUVirtualAddress();
ibView.Format = DXGI_FORMAT_R16_UINT;
//ibView.SizeInBytes = sizeof(indices);
ibView.SizeInBytes = sizeIB;
}
void Model::LoadPMDFile(const char* path)
{
this->modeldata = PMD;
//PMDwb_\
struct PMDHeader {
float version; //F00 00 80 3F == 1.00
char model_name[20];//f
char comment[256];//fRg
};
char signature[3];
PMDHeader pmdheader = {};
string strModelPath = path;
FILE* fp = NULL;
//if (fopen_s(&fp, path, "rb") != 0) {
// return;
//}
fp = fopen(path, "rb");
//auto fp = fopen(strModelPath.c_str(), "rb");
if (fp == nullptr) {
//G[
assert(0);
}
fread(signature, sizeof(signature), 1, fp);
fread(&pmdheader, sizeof(pmdheader), 1, fp);
unsigned int vertNum;//_
fread(&vertNum, sizeof(vertNum), 1, fp);
#pragma pack(1)//1oCgpbLOcACg͔Ȃ
//PMD}eA\
struct PMDMaterial {
XMFLOAT3 diffuse; //fBt[YF
float alpha; // fBt[Y
float specularity;//XyL̋(Zl)
XMFLOAT3 specular; //XyLF
XMFLOAT3 ambient; //ArGgF
unsigned char toonIdx; //gD[ԍ(q)
unsigned char edgeFlg;//}eA̗֊stO
//2oCg̃pfBOII
unsigned int indicesNum; //̃}eA蓖CfbNX
char texFilePath[20]; //eNX`t@C(vXAt@cq)
};//70oCĝ͂cłpfBO邽72oCg
#pragma pack()//1oCgpbLO
constexpr unsigned int pmdvertex_size = 38;//_1̃TCY
std::vector<unsigned char> vertices(vertNum*pmdvertex_size);//obt@m
fread(vertices.data(), vertices.size(), 1, fp);//Cɓǂݍ
//unsigned int indicesNum;//CfbNX
fread(&indicesNum, sizeof(indicesNum), 1, fp);//
//UPLOAD(mۂ͉\)
auto result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(vertices.size()),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&vertBuff));
unsigned char* vertMap = nullptr;
result = vertBuff->Map(0, nullptr, (void**)&vertMap);
std::copy(vertices.begin(), vertices.end(), vertMap);
vertBuff->Unmap(0, nullptr);
vbView.BufferLocation = vertBuff->GetGPUVirtualAddress();//obt@̉zAhX
vbView.SizeInBytes = vertices.size();//SoCg
vbView.StrideInBytes = pmdvertex_size;//1_̃oCg
std::vector<unsigned short>indices(indicesNum);
fread(indices.data(), indices.size() * sizeof(indices[0]), 1, fp);//Cɓǂݍ
auto a = (UINT)indices.size();
//ݒ́Aobt@̃TCYȊO_obt@̐ݒg܂킵
//OKƎv܂B
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(indices.size() * sizeof(indices[0])),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&indexBuff));
//obt@ɃCfbNXf[^Rs[
unsigned short* mappedIdx = nullptr;
indexBuff->Map(0, nullptr, (void**)&mappedIdx);
std::copy(indices.begin(), indices.end(), mappedIdx);
indexBuff->Unmap(0, nullptr);
//CfbNXobt@r[쐬
ibView.BufferLocation = indexBuff->GetGPUVirtualAddress();
ibView.Format = DXGI_FORMAT_R16_UINT;
ibView.SizeInBytes = indices.size() * sizeof(indices[0]);
unsigned int materialNum;
fread(&materialNum, sizeof(materialNum), 1, fp);
materials.resize(materialNum);
textureResources.resize(materialNum);
sphResources.resize(materialNum);
spaResources.resize(materialNum);
toonResources.resize(materialNum);
std::vector<PMDMaterial> pmdMaterials(materialNum);
fread(pmdMaterials.data(), pmdMaterials.size() * sizeof(PMDMaterial), 1, fp);
//Rs[
for (int i = 0; i < pmdMaterials.size(); ++i) {
materials[i].indicesNum = pmdMaterials[i].indicesNum;
materials[i].pmdmaterial.pmddiffuse = pmdMaterials[i].diffuse;
materials[i].pmdmaterial.pmdalpha = pmdMaterials[i].alpha;
materials[i].pmdmaterial.pmdspecular = pmdMaterials[i].specular;
materials[i].pmdmaterial.pmdspecularity = pmdMaterials[i].specularity;
materials[i].pmdmaterial.pmdambient = pmdMaterials[i].ambient;
materials[i].pmdadditional.toonIdx = pmdMaterials[i].toonIdx;
}
for (int i = 0; i < pmdMaterials.size(); ++i) {
//gD[\[X̓ǂݍ
char toonFilePath[32];
sprintf(toonFilePath, "toon/toon%02d.bmp", pmdMaterials[i].toonIdx + 1);
toonResources[i] = GetTextureByPath(toonFilePath);
if (strlen(pmdMaterials[i].texFilePath) == 0) {
textureResources[i] = nullptr;
continue;
}
string texFileName = pmdMaterials[i].texFilePath;
string sphFileName = "";
string spaFileName = "";
if (count(texFileName.begin(), texFileName.end(), '*') > 0) {//Xvb^
auto namepair = SplitFileName(texFileName);
if (GetExtension(namepair.first) == "sph") {
texFileName = namepair.second;
sphFileName = namepair.first;
}
else if (GetExtension(namepair.first) == "spa") {
texFileName = namepair.second;
spaFileName = namepair.first;
}
else {
texFileName = namepair.first;
if (GetExtension(namepair.second) == "sph") {
sphFileName = namepair.second;
}
else if (GetExtension(namepair.second) == "spa") {
spaFileName = namepair.second;
}
}
}
else {
if (GetExtension(pmdMaterials[i].texFilePath) == "sph") {
sphFileName = pmdMaterials[i].texFilePath;
texFileName = "";
}
else if (GetExtension(pmdMaterials[i].texFilePath) == "spa") {
spaFileName = pmdMaterials[i].texFilePath;
texFileName = "";
}
else {
texFileName = pmdMaterials[i].texFilePath;
}
}
//fƃeNX`pXAvP[ṼeNX`pX
if (texFileName != "") {
auto texFilePath = GetTexturePathFromModelAndTexPath(strModelPath, texFileName.c_str());
textureResources[i] = GetTextureByPath(texFilePath.c_str());
}
if (sphFileName != "") {
auto sphFilePath = GetTexturePathFromModelAndTexPath(strModelPath, sphFileName.c_str());
sphResources[i] = GetTextureByPath(sphFilePath.c_str());
}
if (spaFileName != "") {
auto spaFilePath = GetTexturePathFromModelAndTexPath(strModelPath, spaFileName.c_str());
spaResources[i] = GetTextureByPath(spaFilePath.c_str());
}
}
unsigned short boneNum = 0;
fread(&boneNum, sizeof(boneNum), 1, fp);
#pragma pack(1)
//ǂݍݗp{[\
struct Bone {
char boneName[20];//{[
unsigned short parentNo;//e{[ԍ
unsigned short nextNo;//[̃{[ԍ
unsigned char type;//{[
unsigned short ikBoneNo;//IK{[ԍ
XMFLOAT3 pos;//{[̊_W
};
#pragma pack()
vector<Bone> pmdBones(boneNum);
fread(pmdBones.data(), sizeof(Bone), boneNum, fp);
fclose(fp);
//CfbNXƖȎΉW\ẑ߂ɌŎg
vector<string> boneNames(pmdBones.size());
//{[m[h}bv
for (int idx = 0; idx < pmdBones.size(); ++idx) {
auto& pb = pmdBones[idx];
boneNames[idx] = pb.boneName;
auto& node = _boneNodeTable[pb.boneName];
node.boneIdx = idx;
node.startPos = pb.pos;
}
//eqW\z
for (auto& pb : pmdBones) {
//eCfbNX`FbN(蓾ȂԍȂ)
if (pb.parentNo >= pmdBones.size()) {
continue;
}
auto parentName = boneNames[pb.parentNo];
_boneNodeTable[parentName].children.emplace_back(&_boneNodeTable[pb.boneName]);
}
_boneMatrices.resize(pmdBones.size());
//{[ׂďB
std::fill(_boneMatrices.begin(), _boneMatrices.end(), XMMatrixIdentity());
////VMD
//fseek(fp, 50, SEEK_SET);//ŏ50oCg
//unsigned int motionDataNum = 0;
//fread(&motionDataNum, sizeof(motionDataNum), 1, fp);
//struct VMDMotion {
// char boneName[15]; // {[
// unsigned int frameNo; // t[ԍ(Ǎ݂͌̃t[ʒu0ƂΈʒu)
// XMFLOAT3 location; // ʒu
// XMFLOAT4 quaternion; // Quaternion // ]
// unsigned char bezier[64]; // [4][4][4] xWF⊮p[^
//};
//std::vector<VMDMotion> vmdMotionData(motionDataNum);
//for (auto& motion : vmdMotionData)
//{
// fread(motion.boneName, sizeof(motion.boneName), 1, fp);//{[
// fread(&motion.frameNo,
// sizeof(motion.frameNo)//t[ԍ
// + sizeof(motion.location)//ʒu(IK̂ƂɎgp\)
// + sizeof(motion.quaternion)//NI[^jI
// + sizeof(motion.bezier), //ԃxWFf[^
// 1,
// fp);
//};
////VMD̃L[t[f[^AۂɎgpL[t[e[u֕ϊ
//for (auto& vmdMotion : vmdMotionData) {
// _motiondata[vmdMotion.boneName].emplace_back(Motion(vmdMotion.frameNo, XMLoadFloat4(&vmdMotion.quaternion)));
//}
//for (auto& bonemotion : _motiondata)
//{
// auto node = _boneNodeTable[bonemotion.first];
// auto& pos = node.startPos;
// auto mat = XMMatrixTranslation(-pos.x, -pos.y, -pos.z)
// * XMMatrixRotationQuaternion(bonemotion.second[0].quaternion)
// * XMMatrixTranslation(pos.x, pos.y, pos.z);
// _boneMatrices[node.boneIdx] = mat;
//}
}
bool Model::LoadTexture(UINT texNumber, const std::string & directoryPath, const std::string & filename)
{
HRESULT result = S_FALSE;
// WICeNX`̃[h
TexMetadata metadata{};
ScratchImage scratchImg{};
//t@CpX
string filepath = directoryPath + filename;
//jR[hɕϊ
wchar_t wfilepath[128];
int iBufferSize = MultiByteToWideChar(CP_ACP, 0,
filepath.c_str(), -1, wfilepath, _countof(wfilepath));
directoryPath + filename;
//result = LoadFromWICFile(
// L"Resources/texture.png", WIC_FLAGS_NONE,
// &metadata, scratchImg);
result = LoadFromWICFile(
wfilepath, WIC_FLAGS_NONE,
&metadata, scratchImg
);
if (FAILED(result)) {
return result;
}
const Image* img = scratchImg.GetImage(0, 0, 0); // f[^o
// \[Xݒ
CD3DX12_RESOURCE_DESC texresDesc = CD3DX12_RESOURCE_DESC::Tex2D(
metadata.format,
metadata.width,
(UINT)metadata.height,
(UINT16)metadata.arraySize,
(UINT16)metadata.mipLevels
);
// eNX`pobt@̐
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0),
D3D12_HEAP_FLAG_NONE,
&texresDesc,
D3D12_RESOURCE_STATE_GENERIC_READ, // eNX`pw
nullptr,
IID_PPV_ARGS(&texbuff[texNumber]));
if (FAILED(result)) {
return result;
}
// eNX`obt@Ƀf[^]
result = texbuff[texNumber]->WriteToSubresource(
0,
nullptr, // S̈փRs[
img->pixels, // f[^AhX
(UINT)img->rowPitch, // 1CTCY
(UINT)img->slicePitch // 1TCY
);
if (FAILED(result)) {
return result;
}
// VF[_\[Xr[쐬
cpuDescHandleSRV = CD3DX12_CPU_DESCRIPTOR_HANDLE(descHeap->GetCPUDescriptorHandleForHeapStart(), texNumber, descriptorHandleIncrementSize);
//gpuDescHandleSRV = CD3DX12_GPU_DESCRIPTOR_HANDLE(descHeap->GetGPUDescriptorHandleForHeapStart(), texNumber, descriptorHandleIncrementSize);
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc{}; // ݒ\
D3D12_RESOURCE_DESC resDesc = texbuff[texNumber]->GetDesc();
srvDesc.Format = resDesc.Format;
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;//2DeNX`
srvDesc.Texture2D.MipLevels = 1;
device->CreateShaderResourceView(texbuff[texNumber].Get(), //r[Ɗ֘Atobt@
&srvDesc, //eNX`ݒ
cpuDescHandleSRV
);
}
void Model::LoadMaterial(UINT texNumber, const std::string & directoryPath, const std::string & filename)
{
//t@CXg[
std::ifstream file;
//}eAt@CJ
file.open(directoryPath + filename);
//t@CI[vs`FbN
if (file.fail()) {
assert(0);
}
//assert(!file.fail());
//1sǂݍ
string line;
while (getline(file, line)) {
//1s̕Xg[ɕϊ
std::istringstream line_stream(line);
//pXy[Xōs̐擪擾
string key;
getline(line_stream, key, ' ');
//擪̃^u͖
if (key[0] == '\t') {
key.erase(key.begin());//擪̕폜
}
//擪newmtlȂ}eA
if (key == "newmtl") {
//}eAǂݍ
line_stream >> material.name;
}
//擪KaȂArGgF
if (key == "Ka") {
line_stream >> material.ambient.x;
line_stream >> material.ambient.y;
line_stream >> material.ambient.z;
}
//擪KdȂfBt[YF
if (key == "Kd") {
line_stream >> material.diffuse.x;
line_stream >> material.diffuse.y;
line_stream >> material.diffuse.z;
}
//擪KaȂXyL[F
if (key == "Ks") {
line_stream >> material.specular.x;
line_stream >> material.specular.y;
line_stream >> material.specular.z;
}
//擪map_KdȂeNX`t@C
if (key == "map_Kd") {
//eNX`̃t@Cǂݍ
line_stream >> material.textureFilename;
//eNX`ǂݍ
LoadTexture(texNumber, directoryPath, material.textureFilename);
}
}
//t@C
file.close();
}
Model::Model(UINT texNumber)
{
this->texnumber = texNumber;
CreateTextureLoaderTable();
this->whiteTex = CreateWhiteTexture();
this->blackTex = CreateBlackTexture();
this->gradTex = CreateGrayGradationTexture();
}
Model * Model::CreateFromOBJ(UINT texNumber, const std::string& modelname)
{
Model* model = new Model(texNumber);
if (model == nullptr) {
return nullptr;
}
model->CreateModel(texNumber, modelname);
//
if (!model->Initialize()) {
delete model;
assert(0);
return nullptr;
}
return model;
}
Model * Model::CreateFromPMD(UINT texNumber, const char* modelname)
{
Model* model = new Model(texNumber);
if (model == nullptr) {
return nullptr;
}
model->LoadPMDFile(modelname);
model->transform.world = XMMatrixIdentity();
model->CreateTransformView();
model->CreateMaterialData();
model->CreateMaterialAndTextureView();
//
if (!model->Initialize()) {
delete model;
assert(0);
return nullptr;
}
return model;
}
bool Model::Initialize()
{
// nullptr`FbN
assert(device);
HRESULT result;
// 萔obt@̐
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // Abv[h\
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer((sizeof(ConstBufferDataB1) + 0xff)&~0xff),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&constBuffB1));
// 萔obt@̐
result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // Abv[h\
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer((sizeof(SceneData) + 0xff)&~0xff),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&cameraconstBuff));
return true;
}
void Model::Update()
{
// nullptr`FbN
assert(device);
HRESULT result;
//萔obt@փf[^]
ConstBufferDataB1* constMap1 = nullptr;
SceneData* cameraconstMap = nullptr;
switch (modeldata)
{
case OBJ:
result = constBuffB1->Map(0, nullptr, (void**)&constMap1);
constMap1->ambient = material.ambient;
constMap1->diffuse = material.diffuse;
constMap1->specular = material.specular;
constMap1->alpha = material.alpha;
constBuffB1->Unmap(0, nullptr);
break;
case PMD:
angle += 0.03f;
_mappedMatrices[0] = XMMatrixRotationY(angle)*Camera::matView*Camera::matProjection;
result = cameraconstBuff->Map(0, nullptr, (void**)&cameraconstMap);
cameraconstMap->view = Camera::matView;
cameraconstMap->proj = Camera::matProjection;
cameraconstMap->eye = Camera::eye;
cameraconstMap->viewproj = Camera::matView*Camera::matProjection;
cameraconstBuff->Unmap(0, nullptr);
break;
default:
break;
}
}
void Model::Draw(ID3D12GraphicsCommandList* cmdList,
ComPtr<ID3D12Resource> constBuffB0)
{
// _obt@̐ݒ
cmdList->IASetVertexBuffers(0, 1, &vbView);
// CfbNXobt@̐ݒ
cmdList->IASetIndexBuffer(&ibView);
//PMDp
if (modeldata == PMD)
{
// fXNv^q[v̔z
ID3D12DescriptorHeap* transheaps[] = { transformHeap.Get() };
cmdList->SetDescriptorHeaps(1, transheaps);
cmdList->SetGraphicsRootDescriptorTable(1, transformHeap->GetGPUDescriptorHandleForHeapStart());
//}eAq[v
ID3D12DescriptorHeap* mdh[] = { materialHeap.Get() };
//}eA
cmdList->SetDescriptorHeaps(1, mdh);
auto materialH = materialHeap->GetGPUDescriptorHandleForHeapStart();
unsigned int idxOffset = 0;
auto cbvsrvIncSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) * 5;
for (auto& m : materials) {
cmdList->SetGraphicsRootDescriptorTable(2, materialH);
cmdList->DrawIndexedInstanced(m.indicesNum, 1, idxOffset, 0, 0);
materialH.ptr += cbvsrvIncSize;
idxOffset += m.indicesNum;
}
}
if (modeldata == OBJ)
{
//OBJp
ID3D12DescriptorHeap* ppHeaps[] = { descHeap.Get() };
cmdList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps);
// 萔obt@r[Zbg
cmdList->SetGraphicsRootConstantBufferView(0, constBuffB0->GetGPUVirtualAddress());
cmdList->SetGraphicsRootConstantBufferView(1, constBuffB1->GetGPUVirtualAddress());
// VF[_\[Xr[Zbg
cmdList->SetGraphicsRootDescriptorTable(2, CD3DX12_GPU_DESCRIPTOR_HANDLE(descHeap->GetGPUDescriptorHandleForHeapStart(), this->texnumber, descriptorHandleIncrementSize));
cmdList->DrawIndexedInstanced((UINT)modelindices.size(), 1, 0, 0, 0);
}
}
#pragma region PMDp
HRESULT Model::CreateMaterialAndTextureView()
{
D3D12_DESCRIPTOR_HEAP_DESC materialDescHeapDesc = {};
materialDescHeapDesc.NumDescriptors = materials.size() * 5;//}eAԂ(萔1AeNX`3)
materialDescHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
materialDescHeapDesc.NodeMask = 0;
materialDescHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;//fXNv^q[v
HRESULT result = device->CreateDescriptorHeap(&materialDescHeapDesc, IID_PPV_ARGS(materialHeap.ReleaseAndGetAddressOf()));//
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
auto materialBuffSize = sizeof(MaterialForHlsl);
materialBuffSize = (materialBuffSize + 0xff)&~0xff;
D3D12_CONSTANT_BUFFER_VIEW_DESC matCBVDesc = {};
matCBVDesc.BufferLocation = materialBuff->GetGPUVirtualAddress();
matCBVDesc.SizeInBytes = materialBuffSize;
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;//q
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;//2DeNX`
srvDesc.Texture2D.MipLevels = 1;//~bv}bv͎gpȂ̂1
CD3DX12_CPU_DESCRIPTOR_HANDLE matDescHeapH(materialHeap->GetCPUDescriptorHandleForHeapStart());
auto incSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
for (int i = 0; i < materials.size(); ++i) {
//}eAŒobt@r[
device->CreateConstantBufferView(&matCBVDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
matCBVDesc.BufferLocation += materialBuffSize;
if (textureResources[i] == nullptr) {
srvDesc.Format = whiteTex->GetDesc().Format;
device->CreateShaderResourceView(whiteTex.Get(), &srvDesc, matDescHeapH);
}
else {
srvDesc.Format = textureResources[i]->GetDesc().Format;
device->CreateShaderResourceView(textureResources[i].Get(), &srvDesc, matDescHeapH);
}
matDescHeapH.Offset(incSize);
if (sphResources[i] == nullptr) {
srvDesc.Format = whiteTex->GetDesc().Format;
device->CreateShaderResourceView(whiteTex.Get(), &srvDesc, matDescHeapH);
}
else {
srvDesc.Format = sphResources[i]->GetDesc().Format;
device->CreateShaderResourceView(sphResources[i].Get(), &srvDesc, matDescHeapH);
}
matDescHeapH.ptr += incSize;
if (spaResources[i] == nullptr) {
srvDesc.Format = blackTex->GetDesc().Format;
device->CreateShaderResourceView(blackTex.Get(), &srvDesc, matDescHeapH);
}
else {
srvDesc.Format = spaResources[i]->GetDesc().Format;
device->CreateShaderResourceView(spaResources[i].Get(), &srvDesc, matDescHeapH);
}
matDescHeapH.ptr += incSize;
if (toonResources[i] == nullptr) {
srvDesc.Format = gradTex->GetDesc().Format;
device->CreateShaderResourceView(gradTex.Get(), &srvDesc, matDescHeapH);
}
else {
srvDesc.Format = toonResources[i]->GetDesc().Format;
device->CreateShaderResourceView(toonResources[i].Get(), &srvDesc, matDescHeapH);
}
matDescHeapH.ptr += incSize;
}
}
HRESULT Model::CreateMaterialData()
{
//}eAobt@쐬
auto materialBuffSize = sizeof(MaterialForHlsl);
materialBuffSize = (materialBuffSize + 0xff)&~0xff;
auto result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(materialBuffSize*materials.size()),//ܑ̂ȂǎdȂł
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(materialBuff.ReleaseAndGetAddressOf())
);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
//}bv}eAɃRs[
char* mapMaterial = nullptr;
result = materialBuff->Map(0, nullptr, (void**)&mapMaterial);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
for (auto& m : materials) {
*((MaterialForHlsl*)mapMaterial) = m.pmdmaterial;//f[^Rs[
mapMaterial += materialBuffSize;//̃ACgʒu܂Ői߂
}
materialBuff->Unmap(0, nullptr);
return S_OK;
}
HRESULT Model::CreateTransformView()
{
//GPUobt@쐬
auto buffSize = sizeof(XMMATRIX)*(1 + _boneMatrices.size());
buffSize = (buffSize + 0xff)&~0xff;
auto result = device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(buffSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(transformBuff.ReleaseAndGetAddressOf())
);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
//}bvƃRs[
result = transformBuff->Map(0, nullptr, (void**)&_mappedMatrices);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
_mappedMatrices[0] = transform.world;
auto node = _boneNodeTable["r"];
auto& pos = node.startPos;
_boneMatrices[node.boneIdx] = XMMatrixTranslation(-pos.x, -pos.y, -pos.z)
* XMMatrixRotationZ(XM_PIDIV2)
* XMMatrixTranslation(pos.x, pos.y, pos.z);
copy(_boneMatrices.begin(), _boneMatrices.end(), _mappedMatrices + 1);
//r[̍쐬
D3D12_DESCRIPTOR_HEAP_DESC transformDescHeapDesc = {};
transformDescHeapDesc.NumDescriptors = 1;//Ƃ肠[hЂƂ
transformDescHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
transformDescHeapDesc.NodeMask = 0;
transformDescHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;//fXNv^q[v
result = device->CreateDescriptorHeap(&transformDescHeapDesc, IID_PPV_ARGS(transformHeap.ReleaseAndGetAddressOf()));//
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
cbvDesc.BufferLocation = transformBuff->GetGPUVirtualAddress();
cbvDesc.SizeInBytes = buffSize;
device->CreateConstantBufferView(&cbvDesc, transformHeap->GetCPUDescriptorHandleForHeapStart());
return S_OK;
}
ComPtr<ID3D12Resource> Model::GetTextureByPath(const char * texpath)
{
auto it = _textureTable.find(texpath);
if (it != _textureTable.end()) {
//e[uɓɂ烍[ĥł͂Ȃ}bv
//\[XԂ
return _textureTable[texpath];
}
else {
return ComPtr<ID3D12Resource>(CreateTextureFromFile(texpath));
}
}
ID3D12Resource * Model::CreateTextureFromFile(const char * texpath)
{
string texPath = texpath;
//eNX`̃[h
TexMetadata metadata = {};
ScratchImage scratchImg = {};
auto wtexpath = GetWideStringFromString(texPath);//eNX`̃t@CpX
auto ext = GetExtension(texPath);//gq擾
auto result = loadLambdaTable[ext](wtexpath,
&metadata,
scratchImg);
if (FAILED(result)) {
return nullptr;
}
auto img = scratchImg.GetImage(0, 0, 0);//f[^o
//WriteToSubresourceœ]p̃q[vݒ
auto texHeapProp = CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0);
auto resDesc = CD3DX12_RESOURCE_DESC::Tex2D(metadata.format, metadata.width, metadata.height, metadata.arraySize, metadata.mipLevels);
ID3D12Resource* texbuff = nullptr;
result = device->CreateCommittedResource(
&texHeapProp,
D3D12_HEAP_FLAG_NONE,//ɎwȂ
&resDesc,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
nullptr,
IID_PPV_ARGS(&texbuff)
);
if (FAILED(result)) {
return nullptr;
}
result = texbuff->WriteToSubresource(0,
nullptr,//S̈փRs[
img->pixels,//f[^AhX
img->rowPitch,//1CTCY
img->slicePitch//STCY
);
if (FAILED(result)) {
return nullptr;
}
return texbuff;
}
void Model::CreateTextureLoaderTable()
{
loadLambdaTable["sph"] = loadLambdaTable["spa"] = loadLambdaTable["bmp"] = loadLambdaTable["png"] = loadLambdaTable["jpg"] = [](const wstring& path, TexMetadata* meta, ScratchImage& img)->HRESULT {
return LoadFromWICFile(path.c_str(), WIC_FLAGS_NONE, meta, img);
};
loadLambdaTable["tga"] = [](const wstring& path, TexMetadata* meta, ScratchImage& img)->HRESULT {
return LoadFromTGAFile(path.c_str(), meta, img);
};
loadLambdaTable["dds"] = [](const wstring& path, TexMetadata* meta, ScratchImage& img)->HRESULT {
return LoadFromDDSFile(path.c_str(), DDS_FLAGS_NONE, meta, img);
};
}
ID3D12Resource * Model::CreateDefaultTexture(size_t width, size_t height)
{
auto resDesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R8G8B8A8_UNORM, width, height);
auto texHeapProp = CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0);
ID3D12Resource* buff = nullptr;
auto result = device->CreateCommittedResource(
&texHeapProp,
D3D12_HEAP_FLAG_NONE,//ɎwȂ
&resDesc,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
nullptr,
IID_PPV_ARGS(&buff)
);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return nullptr;
}
return buff;
}
ID3D12Resource * Model::CreateWhiteTexture()
{
ID3D12Resource* whiteBuff = CreateDefaultTexture(4, 4);
std::vector<unsigned char> data(4 * 4 * 4);
std::fill(data.begin(), data.end(), 0xff);
auto result = whiteBuff->WriteToSubresource(0, nullptr, data.data(), 4 * 4, data.size());
assert(SUCCEEDED(result));
return whiteBuff;
}
ID3D12Resource * Model::CreateBlackTexture()
{
ID3D12Resource* blackBuff = CreateDefaultTexture(4, 4);
std::vector<unsigned char> data(4 * 4 * 4);
std::fill(data.begin(), data.end(), 0x00);
auto result = blackBuff->WriteToSubresource(0, nullptr, data.data(), 4 * 4, data.size());
assert(SUCCEEDED(result));
return blackBuff;
}
ID3D12Resource * Model::CreateGrayGradationTexture()
{
ID3D12Resource* gradBuff = CreateDefaultTexture(4, 256);
//オĉeNX`f[^쐬
std::vector<unsigned int> data(4 * 256);
auto it = data.begin();
unsigned int c = 0xff;
for (; it != data.end(); it += 4) {
auto col = (0xff << 24) | RGB(c, c, c);//RGBAtтĂ邽RGB}N0xff<<24pĕ\B
std::fill(it, it + 4, col);
--c;
}
auto result = gradBuff->WriteToSubresource(0, nullptr, data.data(), 4 * sizeof(unsigned int), sizeof(unsigned int)*data.size());
assert(SUCCEEDED(result));
return gradBuff;
}
#pragma endregion | true |
7c9717a5ef4d85109816b369938babe1da1579dd | C++ | ahmostthere/LittleLeaf | /test/blendModeTests.hpp | UTF-8 | 6,179 | 2.59375 | 3 | [] | no_license | // #include "SomeTest.hpp"
// #include "Test2.hpp"
// void start()
// {
// Testing::load();
// while(!Testing::quitting())
// {
// Testing::resetTimer();
// Testing::handleInput();
// Testing::update();
// Testing::render();
// }
// Testing::quit();
// }
// int main()
// {
// start();
// return 0;
// }
#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>
#include <cmath>
sf::VertexArray createVA(sf::Vector2f pos, float rad, sf::Color outerColor, sf::Color innerColor, int slices = 100, float percentage = .5 )
{
sf::VertexArray retVal(sf::Quads);
float pi = std::acos(-1);
for (int i = 0; i < slices; i++)
{
// Q outer
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad, sin((2 * pi * (i) / slices) - pi / 2) * rad), outerColor));
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad, sin((2 * pi * (i + 1) / slices) - pi / 2) * rad), outerColor));
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage), innerColor));
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i) / slices) - pi / 2) * rad * percentage), innerColor));
// Q inner
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i) / slices) - pi / 2) * rad * percentage), innerColor));
retVal.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage), innerColor));
retVal.append(sf::Vertex(pos, innerColor)); // center
retVal.append(sf::Vertex(pos, innerColor)); // center
}
return retVal;
}
int main2()
{
sf::RenderWindow app(sf::VideoMode(800u, 600u), "blending lights");
app.setFramerateLimit(60u);
sf::RenderTexture tex;
tex.create(app.getSize().x, app.getSize().y);
sf::Texture pic;
pic.loadFromFile("assets/menuSplash.png");
sf::Texture pic2;
pic2.loadFromFile("assets/arrowButtons.png");
std::vector<sf::Vector2f> lights;
std::vector<sf::Vector2f> lightsAlpha;
const sf::Color colors[3] = {sf::Color::Red, sf::Color::Green, sf::Color::Blue};
while (app.isOpen())
{
sf::Event eve;
while (app.pollEvent(eve))
{
if (eve.type == sf::Event::Closed)
app.close();
if (eve.type == sf::Event::MouseButtonPressed)
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
lights.push_back(app.mapPixelToCoords(sf::Vector2i(eve.mouseButton.x, eve.mouseButton.y)));
}
}
if (eve.type == sf::Event::KeyPressed)
{
switch (eve.key.code)
{
case sf::Keyboard::Escape:
app.close();
break;
case sf::Keyboard::Space:
lightsAlpha.push_back(app.mapPixelToCoords(sf::Mouse::getPosition(app)));
break;
}
}
}
app.clear();
// start = no light
tex.clear(sf::Color(80, 60, 120));
// sf::VertexArray sha2(sf::Quads);
// sf::Vector2f pos = app.mapPixelToCoords(sf::Mouse::getPosition(app));
// float rad = 250.f;
// int slices = 100;
// float percentage = .5;
// float pi = std::acos(-1);
// for (int i = 0; i < slices; i++)
// {
// // Q outer
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad, sin((2 * pi * (i) / slices) - pi/2) * rad), sf::Color::Transparent));
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad, sin((2 * pi * (i + 1) / slices) - pi/2) * rad), sf::Color::Transparent));
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i + 1) / slices) - pi/2) * rad * percentage), sf::Color::White));
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i) / slices) - pi/2) * rad * percentage), sf::Color::White));
// // Q inner
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i) / slices) - pi/2) * rad * percentage), sf::Color::White));
// sha2.append(sf::Vertex(pos + sf::Vector2f(cos((2 * pi * (i + 1) / slices) - pi / 2) * rad * percentage, sin((2 * pi * (i + 1) / slices) - pi/2) * rad * percentage), sf::Color::White));
// sha2.append(sf::Vertex(pos, sf::Color::White)); // center
// sha2.append(sf::Vertex(pos, sf::Color::White)); // center
// }
sf::VertexArray sha2 = createVA(app.mapPixelToCoords(sf::Mouse::getPosition(app)), 250.f, sf::Color::Transparent, sf::Color(0xc2, 0x7e, 0x00));
tex.draw(sha2, sf::BlendAdd);
for (int i = 0; i < lightsAlpha.size(); ++i)
{
sha2 = createVA(lightsAlpha[i], 250.f, sf::Color(0, 0, 0, 0x55), sf::Color(0xff, 0xff, 0xff, 0x55));
tex.draw(sha2, sf::BlendAlpha);
}
// add the lights together
for (int i = 0; i < lights.size(); ++i)
{
sha2 = createVA(lights[i], 250.f, sf::Color::Transparent, colors[i % 3]);
tex.draw(sha2, sf::BlendAdd);
}
tex.draw(sf::Sprite(pic2), sf::BlendAlpha);
tex.display();
// lit scene
app.draw(sf::Sprite(pic));
// app.draw(sf::Sprite(pic2));
// multiply by light
app.draw(sf::Sprite(tex.getTexture()), sf::BlendMultiply);
app.display();
}
return 0;
} | true |
26c499276b502a64af594887e93260383f0462eb | C++ | ajaykarthik/unixv6 | /unixv6.cc | UTF-8 | 26,592 | 2.8125 | 3 | [] | no_license | /*****************************************************************************************************************
Operating Systems project 2
Ajay Karthik Ganesan and Ashwin Rameshkumar
This program, when run creates a virtual unix file system, which removes the V-6 file system size limit of 16MB
Compiled and run on cs3.utdallas.edu
compile as CC fsaccess.cc and run as ./a.out
Max file size is 12.5 GB
******************************************************************************************************************/
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <iostream.h>
#include <fstream.h>
#include<vector>
//for file size
#include <sys/stat.h>
using namespace std;
//Global constants
const block_Size = 2048; //Given block size
//Easier to work with global files as we need them in almost all functions and
// we don't need to pass them as parameters every time
int num_iNodes, num_Blocks;
string new_File_System;
int fd;
int next_free_inode = 1; //initialised to 2 , inode 1 is root
//This dynamic memory is written into the file system during the q command and also de-allocated
void *root_dir;
void *super;
long long max_file_size = 13421772800;
//function prototype
off_t fsize(const char *filename);
void test();
/*************************************************************************
struct superblock
Variables same as those in v-6 file-system,
From the given requirements, we consider that there is one i node per block
**************************************************************************/
struct superblock
{
unsigned short isize;
unsigned short fsize;
unsigned short nfree;
unsigned int free[100];
unsigned short ninode;
unsigned int inode[100];
char flock;
char ilock;
char fmod;
unsigned short time[2];
//constructor
superblock()
{
isize = num_iNodes;
fsize = num_Blocks; //First block not potentially available for allocation to a file
ninode = num_iNodes;
//initial n-free value
nfree = 100;
//dummy values for the rest of the variables
flock = 'j';
ilock = 'b';
fmod = 'n';
time[0] = time[1] = 0;
//current_block will be used later
int current_block= (num_iNodes + 3) ;
//Write free data blocks into free[] list
//For example, if num_iNodes is 100, free data blocks start from 103 ( We use one block per iNode)
for (int j=0; (current_block < (num_iNodes + 103)) && (current_block < num_Blocks); current_block++,j++)
{
//Block 0 is unused, block 1 is super-block,block 3 is root directory
//rest of the num_iNodes are blocks allocated for iNodes
//Hence data blocks start from num_iNodes+ 3
free[99-j] = current_block;
//inode[] is not used in this implementation, hence a dummy value is assigned
inode[j] = 0;
}
//i is the first block not written into the free list
//Write next 100 free free data block into the 0th block of the free[] array
//repeat this till the data blocks are exhausted
int first_data_block;
int new_nfree;
int *new_free_array;
while(current_block < num_Blocks)
{
first_data_block = current_block-1;
//lseek to this block and write nfree as first 2 bytes
//Get pointer to block 1
if (lseek(fd,first_data_block * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to first_data_block for assigning new nfree\n";
}
//write nfree
if((num_Blocks - current_block) > 100)
{
new_nfree = 100;
}
else
{
new_nfree = (num_Blocks - current_block) ;
}
new_free_array = new int[new_nfree+1];
new_free_array[0] = new_nfree;
//use current block and write next 100 blocks (if blocks are available)
for(int j=1;j < new_nfree+1 ;j++,current_block++)
{
new_free_array[(new_nfree+1)-j] = current_block ;
}
//Write the whole block, because its easier
if (write(fd, new_free_array ,block_Size) < block_Size)
{
cout << "Error writing new block";
}
delete[] new_free_array;
}
}
/***************************************************************************************************
get the next free data block to assign to a file or directory, if nfree becomes 0 , read
the contents of free[0] and assign first number to nfree and next 100 number to free[] array
Note: No check is made to see if all data blocks are exhausted as this is not part of the requirement
****************************************************************************************************/
int get_next_freeblock()
{
nfree--;
if(nfree == 0)
//bring in contents from free[0] and fill it up as the new nfree and free array
{
int block_to_return = free[0];
if (lseek(fd,free[0] * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to free[0] for reading new nfree\n";
return -1;
}
//max size will be 101
int *new_free_array = new int[101];
if (read(fd, new_free_array ,block_Size) < 0)
{
cout << "Error reading new block";
return -1;
}
nfree=new_free_array[0];
for(int i=0;i<nfree;i++)
{
free[i] = new_free_array[i+1];
}
delete[] new_free_array;
return block_to_return;
}
//Business as usual
else
{
return free[nfree];
}
}
/***************************************************************************************************
return the last free block allocated, used for reference
****************************************************************************************************/
int last_block_used()
{
return free[nfree];
}
//destructor
~superblock()
{
delete[] free;
delete[] inode;
delete[] time;
}
};
/**************************************************************************************
struct inode
Variables same as those in v-6 filesystem, but size of file and addr[]
size values are updated to increase max size
**************************************************************************************/
struct inode
{
unsigned int flags;
char nlinks;
char uid;
char gid;
//Max file size is 12.5GB
unsigned long long int size;
//Each is a double in-direct block
unsigned int addr[25];
unsigned short actime;
unsigned short modtime[2];
//constructor
inode()
{
flags = 004777; //initialized to unallocated, plain small file, set uid on execution, permission for all users is 1
nlinks='0';
uid='1';
gid='2';
size=0;
modtime[0]=0;
modtime[1]=0;
actime=1;
}
};
/**************************************************************************************
struct directory
Used to write the root directory (along with file and sub-directory entries)
and also sub-directories
**************************************************************************************/
struct directory
{
//Entry could be a file or a directory
string *entry_Name ;
int *inode_list;
int inode_iterator;
//Initialise root directory with given name , written to block after the inodes are assigned
directory()
{
entry_Name = new string[num_iNodes+1];
inode_iterator = 0;
inode_list = new int[num_iNodes];
entry_Name[inode_iterator] = new_File_System; // file system name for every directory, including root
inode_list[inode_iterator]=1;// inode of root is 1
inode_iterator++;
entry_Name[inode_iterator] = new_File_System;
inode_list[inode_iterator]=1;
inode_iterator++;
}
//Initialize sub directory (mkdir)
directory(string dir_name)
{
entry_Name = new string[2]; // one for root, one for self
inode_iterator = 0;
inode_list = new int[2];
entry_Name[inode_iterator] = dir_name;
inode_list[inode_iterator] = next_free_inode;
inode_iterator++;
entry_Name[inode_iterator] = new_File_System;
inode_list[inode_iterator] = 1;//root
inode_iterator++;
}
//Delete the dynamic heap memory to prevent leakage
~directory()
{
delete[] inode_list;
delete[] entry_Name;
}
//Entry inside a folder ( Only the root folder has entries in this implementation )
void file_entry(string entry)
{
entry_Name[inode_iterator]= entry;
inode_list[inode_iterator] = next_free_inode;
inode_iterator++;
//return 0;
}
};
/*************************************************************************
function:
initfs returns int so as the return -1 on read,write and seek errors
initialise the virtual file system
Global variables used
path: Path of the file that represents the virtual disk
num_Blocks: number of blocks allocated in total
num_iNodes: number of iNodes ( We store one iNode per block, the remaining
part of each block is not used )
**************************************************************************/
int initfs()
{
int file_System_Size = num_Blocks * 2048; // Size of on block * number of blocks
char *disk_Size_dummy = new char[file_System_Size]; //to fill the disk with 0's
/***************************************************************************
Initialize the file system (all blocks) with '0's
***************************************************************************/
//Set all blocks to '0'
for (int i=0; i < file_System_Size; i++)
{
disk_Size_dummy[i] = '0';
}
//Get pointer to block 0
if (lseek(fd, 0, SEEK_SET) < 0)
{
cout << "Error getting to block 0 for assigning 0's\n";
return -1;
}
//Write 0's to the whole file system
if (write(fd, disk_Size_dummy, file_System_Size) < file_System_Size)
{
cout << "Error writing file system";
return -1;
}
//delete dummy value from heap
delete[] disk_Size_dummy;
/***************************************************************************
Write super block to block 1 of the file system
super block size is 820 bytes (Remaining bytes in the block are unused)
***************************************************************************/
//Create super-block
super = new superblock();
//Get pointer to block 1
if (lseek(fd, block_Size, SEEK_SET) < 0)
{
cout << "Error getting to block 1 for assigning super-block\n";
return -1;
}
//Write super-block onto the file system
if (write(fd, super, sizeof(superblock)) < sizeof(superblock))
{
cout << "Error writing super-block\n";
return -1;
}
/**************************************************************************************
Write iNodes to the file system
One iNode per block, iNode size is 220 bytes (Remaining bytes in the block are unused)
Start from block 2 ( Block 0 is unused and Block 1 superblock )
***************************************************************************************/
//Create an i-node to write num_inode times
inode *temp_iNode = new inode();
for(int i=0; i<num_iNodes; i++)
{
//Get pointer to block i+2
if(lseek(fd, (i+2)*block_Size, SEEK_SET) < 0)
{
cout<<"Error getting to block for writing i nodes\n";
return -1;
}
//Write block i+2 with inode
if(write(fd,temp_iNode,sizeof(inode)) < sizeof(inode))
{
cout<<"Error writing inode number "<<i<<endl;
return -1;
}
}
delete[] temp_iNode;
/**************************************************************************************
Write the root directory information into the first data block
This is used to keep track of the files and directories in the file system
***************************************************************************************/
root_dir = new directory();
//write root directory in the file system
//Get pointer to block i+2
if(lseek(fd, (num_iNodes+ 2)*block_Size, SEEK_SET) < 0)
{
cout<<"Error getting to block for writing root dir\n";
return -1;
}
//Write block i+2 with inode
if(write(fd,root_dir,sizeof(directory)) < sizeof(directory))
{
cout<<"Error writing directory \n";
return -1;
}
/***********************************************************************************************
Create inode for the root directory and write it into block 2 (beginning of inodes)
***********************************************************************************************/
inode *root_inode = new inode();
root_inode->flags = 144777; // i node is allocated and file type is directory
//go to the inode
if (lseek(fd,2 * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to block 0 for assigning 0's\n";
//return -1;
}
//Write root inode
if (write(fd, root_inode, sizeof(inode)) < sizeof(inode))
{
cout << "Error writing root inode";
//return -1;
}
delete[] root_inode;
}
/**************************************************************************************
cpin : create a new file called v6-file in the newly created file system and copy the
contents of the input file into the new file system.
v6-file: input file name
***************************************************************************************/
int cpin ( string v6_file )
{
//file descriptors for the external(input) file
int inputfd;
inputfd = 0;
if((inputfd=open(v6_file.c_str(),O_RDWR)) < -1)
{
cout<<"Error opening input file\n";
return -1;
}
inode *node = new inode();
unsigned long long int filesize ;
filesize = fsize(v6_file.c_str());
node->size = filesize;
if(filesize == 0)
{
cout<<"Error empty file\n";
return -1;
}
//inode for file
next_free_inode++;
int num_blocks_needed_for_file=0;
//calculate the the data blocks required to store the file
num_blocks_needed_for_file = filesize/block_Size;
if(filesize%block_Size != 0) num_blocks_needed_for_file++; //extra data lesser than a block size
if(filesize <= 51200)
//Small file
{
char* input_file_contents = new char[filesize];
// read the file
if (lseek(inputfd, 0 ,SEEK_SET) < 0)
{
cout << "Error seek input file\n";
return -1;
}
if (read(inputfd, input_file_contents ,filesize) < filesize)
{
cout << "Error reading input file\n";
return -1;
}
node->flags = 104777; //allocated, plain , small file
//get contents for the addr[] array
for(int i=0;i<num_blocks_needed_for_file;i++)
{
node->addr[i] = ((superblock*)(super))->get_next_freeblock();
}
//write null values to the remaining addr[]
for(int i=num_blocks_needed_for_file;i<25;i++)
{
node->addr[i] = 0;//null
}
/**********************************************************************************
write inode
**********************************************************************************/
//first inode starts from block 2. (i.e inode 1(root) is in block 2)
if (lseek(fd,(next_free_inode+1) * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to block "<<next_free_inode<<endl;
return -1;
}
if (write(fd, node, sizeof(inode)) < sizeof(inode))
{
cout << "Error writing inode "<<next_free_inode<<endl;
return -1;
}
/**********************************************************************************
write data
**********************************************************************************/
if (lseek(fd,(node->addr[0]) * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to addr[0] small file \n";
return -1;
}
if (write(fd, input_file_contents, filesize) < filesize)
{
cout << "Error writing file "<<endl;
return -1;
}
delete[] input_file_contents;
}
else
//Large file
{
node->flags = 114777; //allocated, plain , large file
//one addr[] stores 512*512 = 262144 blocks
int addr_count_required = num_blocks_needed_for_file/262144 ;
if(num_blocks_needed_for_file%262144!=0)addr_count_required++;
//file size exceeds maximum
if(addr_count_required > 25)
{
cout<<"File size exceeds maximum\n";
return -1;
}
/**********************************************************************************
write addr array
a single address in the addr array can point to 512*512 blocks
**********************************************************************************/
//addr[]
for(int i=0;i<addr_count_required;i++)
{
node->addr[i] = ((superblock*)(super))->get_next_freeblock();
}
//write null values to the remaining addr[]
for(int i=addr_count_required;i<25;i++)
{
node->addr[i] = 0;//null
}
/**********************************************************************************
write inode
**********************************************************************************/
//first inode starts from block 2. (i.e inode 1(root) is in block 2)
if (lseek(fd,(next_free_inode+1) * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to block "<<next_free_inode<<endl;
return -1;
}
if (write(fd, node, sizeof(inode)) < sizeof(inode))
{
cout << "Error writing inode "<<next_free_inode<<endl;
return -1;
}
/**********************************************************************************
write pointers - Level 1
A Single address in a level can point to 512 blocks
**********************************************************************************/
int *blocks_to_assign ;
//assume blocks till addr_count_required would be full (there is some data wastage)
//Level 1
int num_blocks_allocated = 0; // Keep track of num blocks allocated Vs num of blocks in file
blocks_to_assign = new int [512];
for(int i=0;i<addr_count_required;i++)
{
//write 512 addresses into the first indirect block
int j=0;
for(;(j<512) && (num_blocks_allocated<=num_blocks_needed_for_file);j++)
{
blocks_to_assign[j] =((superblock*)(super))->get_next_freeblock();
num_blocks_allocated = num_blocks_allocated + 512;
}
//add zeros if less than 512
for(;j<512;j++)
{
blocks_to_assign[j] = 0;
}
//go to addr[i]
if (lseek(fd, node->addr[i] * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to addr "<<endl;
return -1;
}
//write these free blocks into addr[i]
if (write(fd, blocks_to_assign, block_Size) < block_Size)
{
cout << "Error writing pointers "<<endl;
return -1;
}
}
delete[] blocks_to_assign;
/**********************************************************************************
write pointers - Level 2
A Single address in a level can point to 1 block
**********************************************************************************/
//The starting address is the block next to addr[addr_count_required] as data is sequential
int start = ((node->addr[addr_count_required-1])+1);
int stop = ((superblock*)(super))->last_block_used();
num_blocks_allocated = 0;//reset
blocks_to_assign = new int [512];
for(int i=start ; i<= stop ; i++)
{
//write 512 addresses into the first indirect block
int j=0;
for(;(j<512) && (num_blocks_allocated<=num_blocks_needed_for_file);j++)
{
blocks_to_assign[j] =((superblock*)(super))->get_next_freeblock();
num_blocks_allocated++ ;
}
//add zeros if less than 512
for(;j<512;j++)
{
blocks_to_assign[j] = 0;
}
//go to addr[i]
if (lseek(fd, i * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to addr "<<endl;
return -1;
}
//write these free blocks into addr[i]
if (write(fd, blocks_to_assign, block_Size) < block_Size)
{
cout << "Error writing pointers "<<endl;
return -1;
}
}
delete[] blocks_to_assign;
/**********************************************************************************
read input data
**********************************************************************************/
char* input_file_contents = new char[filesize];
// read the file
if (lseek(inputfd, 0, SEEK_SET) < 0)
{
cout << "Error getting to addr "<<endl;
return -1;
}
if (read(inputfd, input_file_contents ,filesize) < filesize)
{
cout << "Error reading input file\n";
return -1;
}
/**********************************************************************************
write data
**********************************************************************************/
int write_data_from = stop +1; //The starting address is the block next to stop as data is sequential
//go to addr[i]
if (lseek(fd, write_data_from * block_Size, SEEK_SET) < 0)
{
cout << "Error getting to addr "<<endl;
return -1;
}
//write data
if (write(fd, input_file_contents, filesize) < filesize)
{
cout << "Error writing data "<<endl;
return -1;
}
delete[] input_file_contents;
}
//Entry into the root directory
((directory*) root_dir)->file_entry(v6_file.c_str());
delete[] node;
}
/******************************************************************************************************
This function is used to find the file size of the given input file for the cpin function
This function is from the stack overflow website
http://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c
filename: input file name
off_t : returns the size of the file
*******************************************************************************************************/
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
/**************************************************************************************
cpout : create external file if v6 file exists
***************************************************************************************/
void cpout(string v6_file, string externalfile)
{
//Check if v6 file exists
int ilist_match=0;
for(;ilist_match<=((directory*)root_dir)->inode_iterator;ilist_match++)
{
if(((directory*)root_dir)->entry_Name[ilist_match] == v6_file) break;
}
if(ilist_match>=((directory*)root_dir)->inode_iterator)
{
cout<<"File doesn't exist\n";
return;
}
//get inode for the v6 file
int v6_inode = ((directory*)root_dir)->inode_list[ilist_match];
inode *node = new inode();
//inode x is in block x+1
if (lseek(fd, (v6_inode+1) * block_Size ,SEEK_SET) < 0)
{
cout << "Error getting to addr "<<endl;
}
if (read(fd, node ,sizeof(inode)) < sizeof(inode))
{
cout << "Error reading v6 inode\n";
}
//get file size and starting address, file is contiguous
unsigned long long int file_size = node->size;
int starting_addr;
if(file_size <= 51200)
{
starting_addr = node->addr[0];
}
else
{
//get addr[0] block
int *block0 = new int[512];
if (lseek(fd, node->addr[0] * block_Size,SEEK_SET) < 0)
{
cout << "Error getting to starting_addr "<<endl;
}
if (read(fd, block0 ,block_Size) < block_Size)
{
cout << "Error reading input file block0\n";
}
//get first element of block0
int *block1 = new int[512];
if (lseek(fd, block0[0] * block_Size,SEEK_SET) < 0)
{
cout << "Error getting to starting_addr "<<endl;
}
if (read(fd, block1 ,block_Size) < block_Size)
{
cout << "Error reading input file block1\n";
}
starting_addr = block1[0];
delete[] block0;
delete[] block1;
}
char* v6_file_contents = new char[file_size];
//read file
if (lseek(fd, starting_addr * block_Size,SEEK_SET) < 0)
{
cout << "Error getting to starting_addr "<<endl;
}
if (read(fd, v6_file_contents ,file_size) < file_size)
{
cout << "Error reading input file\n";
}
//write output
ofstream file_to_return;;
file_to_return.open(externalfile.c_str());
int external_fd;
if((external_fd=open(externalfile.c_str(),O_RDWR)) < -1)
{
cout<<"Error opening file descriptor for next free inode\n";
}
if (lseek(external_fd, 0,SEEK_SET) < 0)
{
cout << "Error getting to external "<<endl;
}
if (write(external_fd, v6_file_contents ,file_size) < file_size)
{
cout << "Error writing input file\n";
}
file_to_return.close();
delete[] v6_file_contents;
}
/**************************************************************************************
mkdir: create a new directory by the name dirname and store its contents in
root dir ilist and also create an inode
***************************************************************************************/
void mkdir(string dirname)
{
//Check if dir exists
for(int ilist_match=0;ilist_match<=((directory*)root_dir)->inode_iterator;ilist_match++)
{
if(((directory*)root_dir)->entry_Name[ilist_match] == dirname)
{
cout<<"Directory already exists\n";
return;
}
}
//entry in root's ilist
((directory*)root_dir)->file_entry(dirname.c_str());
//inode for dir
next_free_inode++;
//create inode
inode *dir_inode = new inode();
dir_inode->flags = 144777; // allocated, directory, user ID, all access
//get block for storing addr
int block = ((superblock*)(super))->get_next_freeblock();
dir_inode->addr[0] = block;
//write inode in file system
if (lseek(fd, (next_free_inode+1) * block_Size ,SEEK_SET) < 0)
{
cout << "Error getting to inode "<<endl;
}
if (write(fd, dir_inode ,sizeof(inode)) < sizeof(inode))
{
cout << "Error writing input file\n";
}
//create the sub directory
directory* sub_dir = new directory(dirname.c_str());
//write the directory into the file system
if (lseek(fd, block * block_Size ,SEEK_SET) < 0)
{
cout << "Error getting to dir "<<endl;
}
if (write(fd, sub_dir ,sizeof(directory)) < sizeof(directory))
{
cout << "Error writing input file\n";
}
delete[] dir_inode;
}
/**************************************************************************************
quit: save all system data and close
***************************************************************************************/
void quit()
{
//need to save superblock and root directory
//write superblock in file system
if (lseek(fd, block_Size ,SEEK_SET) < 0)
{
cout << "Error getting to inode "<<endl;
}
if (write(fd, (superblock*)super ,sizeof(superblock)) < sizeof(superblock))
{
cout << "Error writing superblock file\n";
}
//write root dir in first block after inodes (this space was initially reserved)
if (lseek(fd,(num_iNodes +1 ) * block_Size ,SEEK_SET) < 0)
{
cout << "Error getting to inode "<<endl;
}
if (write(fd, (directory*)root_dir ,sizeof(directory)) < sizeof(directory))
{
cout << "Error writing directory file\n";
}
}
int main()
{
//temp assignment (get from user)
new_File_System = "testing";
num_iNodes = 300;
num_Blocks = 10000;
ofstream outputFile;
outputFile.open(new_File_System.c_str());
if((fd=open(new_File_System.c_str(),O_RDWR)) < -1)
{
cout<<"Error opening file descriptor for next free inode\n";
return -1;
}
if(initfs() == -1)
{
cout<<"Error initializing file system\n";
return -1;
}
cpin("test.docx");
cpout("test.docx","extern.txt");
mkdir("folder");
outputFile.close();
//temp (add to q)
delete[] root_dir;
delete[] super;
return (0);
}
| true |
a0d21f556657b1e80f7f193aeecb7a1fc88b4032 | C++ | luoxz-ai/codegoogle.gbmath | /normal2.cpp | UTF-8 | 1,292 | 3.015625 | 3 | [
"MIT"
] | permissive |
#include "_gbmath.h"
namespace gbmath
{
normal2& normal2::rotate (const mat22& m)
{
vec2 tmp(_x,_y);
tmp = m * tmp;
_x=tmp.x;
_y=tmp.y;
return *this;
}
float normal2::angle( const normal2& n ) const
{
float fdot = vec2(_x,_y).dot( vec2(n._x , n._y) );
float res = acos(fdot);
return res;
}
normal2& normal2::direction_between( const point2& src , const point2& dst )
{
//vec2 vsrc(src._x , src._y);
//vec2 vdst(dst._x , dst._y);
_x = dst.x() - src.x();
_y = dst.y() - src.y();
return __normalize();
}
normal2& normal2::rotate90Degr( bool clockWise )
{
mat22 mat;
if( clockWise == false )
{
mat.floats [0][0] = 0.0f; // cosine
mat.floats [0][1] = 1.0f; // sine
mat.floats [1][0] = -1.0f; // -sine
mat.floats [1][1] = 0.0f; // cosine
}
else
{
mat.floats [0][0] = 0.0f; // cosine
mat.floats [0][1] = -1.0f; // sine
mat.floats [1][0] = 1.0f; // -sine
mat.floats [1][1] = 0.0f; // cosine
}
vec2 temp = vec2( _x , _y );
temp = mat * temp;
_x = temp.x;
_y = temp.y;
return *this;
}
normal2::operator vec2 () const
{
return vec2(_x,_y);
}
normal2& normal2::operator = (const vec2& a)
{
_x = a.x;
_y = a.y;
return __normalize();
}
}
| true |
3c857b6218d3d5269bb1c2d4af017d7ed11eaff1 | C++ | at97/HomeHerb | /GSMModuleMoistureSensor/GSMModuleMoistureSensor.ino | UTF-8 | 2,968 | 2.84375 | 3 | [] | no_license | //If sms send = TEST then you get a SMS reply to your own phone
#include <SoftwareSerial.h>
// Green wire
int rxPin = 53;
//Blue wire
int txPin = 51;
SoftwareSerial MySerial(rxPin,txPin);
char incomingbyte[150]; // array to compare incoming SMS
int index=0; // array to compare incoming SMS - index
int count=5; // counting to 5 connecting network (Setup setting)
int i=0; // Setup setting
int y=0; // condition to read incoming values
int c=0;
// Soil
// Moisture value
int moistureValue = 0;
//Declare a variable for the soil moisture sensor
int soilPin = A1;
//Variable for Soil moisture Power
int soilPower = 8;
/*The setup will start in 19200 baud both Serial and My Serial, later count until 5 to connect to network and start the AT commands parameters, so
SMS messages and parameters*/
void updateSerial()
{
delay(2000);
while(Serial.available()){
MySerial.write(Serial.read());
}
while(MySerial.available()){
Serial.write(MySerial.read());
}
}
void sendSMS(String msg)
{
MySerial.println("AT+CMGS=\"1XXXXXXXXXX\"");
updateSerial();
MySerial.println(msg);
updateSerial();
MySerial.write(26);
Serial.println();
}
void setup()
{
Serial.begin(9600);
MySerial.begin(9600);
pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
digitalWrite(soilPower, LOW);//Set to LOW so no power is flowing through the sensor
MySerial.println("AT");
updateSerial();
delay(1000);
MySerial.println("AT+CMGF=1");
updateSerial();
delay(200);
MySerial.println("AT+CMGD=1,4");
updateSerial();
delay(700);
MySerial.println("AT+CNMI=1,2,0,0,0");
updateSerial();
delay(200);
sendSMS("Hello, My name is HomeHerb");
}
void loop()
{
//readSoil();
delay (1000);
for(int y=0; y < 150; y++)
{
incomingbyte[y] = 0;
}
if(MySerial.available())
{
int n_char = MySerial.available();
for (int x = 0; x < n_char; x++)
{
incomingbyte[x]=MySerial.read();
}
String C = incomingbyte;
//Serial.println("setup ended");
Serial.print(" ");
Serial.println(C);
Serial.print(" ");
if(strstr(incomingbyte,"Update"))
{
//String moistureValueString = (String)moistureValue;
sendSMS("Moisture String: ");
//sendSMS(moistureValue);
MySerial.println("AT+CMGD=1,4");
updateSerial();
}
}
}
//This is a function used to get the soil moisture content
int readSoil()
{
digitalWrite(soilPower, HIGH);//turn D7 "On"
delay(10);//wait 10 milliseconds
//Read the SIG value form sensor
moistureValue = analogRead(soilPin);
//turn D7 "Off"
digitalWrite(soilPower, LOW);
return moistureValue;
}
| true |
c5f659b34f28a7bc819d739efc1902e404ebf4f9 | C++ | kondratyev-nv/training | /cpp/src/maximize_loot.cpp | UTF-8 | 1,040 | 3.515625 | 4 | [
"Unlicense"
] | permissive | /**
* A thief finds much more loot than his bag can fit. Help him to find the most
* valuable combination of items assuming that any fraction of a loot item can
* be put into his bag. The goal of this code problem is to implement an
* algorithm for the fractional knapsack problem.
*/
#include "maximize_loot.hpp"
#include <algorithm>
using namespace std;
double maximize_loot(int weight_limit, vector<loot_item> const& items) {
vector<loot_item> sorted_items = items;
sort(sorted_items.begin(), sorted_items.end(), [](loot_item const& item1, loot_item const& item2) -> bool {
return (item1.value / (double)item1.weight) > (item2.value / (double)item2.weight);
});
double profit = 0., limit = weight_limit;
auto item = sorted_items.begin();
while (item != sorted_items.end()) {
double available_weight = min((double)item->weight, limit);
limit -= available_weight;
profit += (item->value / (double)item->weight) * available_weight;
item++;
}
return profit;
}
| true |
57643069ee965d4a228f7b326a75bf61d8871f35 | C++ | vergilium/itstep | /ITStepWorks/DesignPatterns/Adapter/ChemicalElementsInformation.cpp | UTF-8 | 798 | 2.890625 | 3 | [] | no_license | #include "ChemicalElementsInformation.h"
#include <algorithm>
ChemicalElementsInformation::ChemicalElementsInformation()
{
}
ChemicalElementsInformation::~ChemicalElementsInformation()
{
}
double ChemicalElementsInformation::GetDensity(string pName) const
{
transform(pName.begin(), pName.end(), pName.begin(), ::tolower);
if (pName == "silicon")
{
return 2.33;
}
else if (pName == "aluminum")
{
return 2.7;
}
else if (pName == "barium")
{
return 3.76;
}
return 0;
}
int ChemicalElementsInformation::GetPositionFromPeriodicTable(string pName) const
{
transform(pName.begin(), pName.end(), pName.begin(), ::tolower);
if (pName == "silicon")
{
return 14;
}
else if (pName == "aluminum")
{
return 13;
}
else if (pName == "barium")
{
return 56;
}
return -1;
}
| true |
e76d3a9fb1b457a1de8d91ae84553953fbecb47d | C++ | tmgarcia/CPPGameEngine | /GameSkeleton/Engine/AStarData/Nodes/Node.h | UTF-8 | 244 | 2.59375 | 3 | [] | no_license | #pragma once
#include <glm\glm.hpp>
using glm::vec3;
class __declspec(dllexport) Node
{
public:
vec3 position;
int numConnections;
Node(vec3 location)
{
position = location;
numConnections = 0;
}
~Node(){}
};
| true |
7826b3e63575b155004971f66fbba00a4315c16a | C++ | nmtrmail/backstroke | /src/rtss/backstroke/rtss-macros.h | UTF-8 | 1,279 | 2.828125 | 3 | [] | no_license | // headers
#define AVPUSH_RESTORE_DISPOSE_HEADER(type,typename) \
private:\
std::deque<std::pair<type*, type> > data_container_##typename; \
inline void restore_##typename();\
inline void dispose_##typename();\
public:\
inline type* avpush(type* address); \
// implementations
#define AVPUSH_RESTORE_DISPOSE_IMPLEMENTATION(type,mytypename,typeenum) \
inline void Backstroke::RunTimeStateStore::restore_##mytypename() {\
std::pair<type*,type> p=data_container_##mytypename.back(); \
data_container_##mytypename.pop_back();\
restore_assignment_inside_macro(p);\
}\
inline void Backstroke::RunTimeStateStore::dispose_##mytypename() {\
data_container_##mytypename.pop_front();\
}\
type* Backstroke::RunTimeStateStore::avpush(type* address) { \
if(!is_stack_ptr(address)) {\
currentEventRecord->stack_bitype.push(typeenum);\
data_container_##mytypename.push_back(std::make_pair(address,*address)); \
}\
return address;\
}\
\
#define CASE_ENUM_RESTORE(enumname,mytypename) \
case BITYPE_##enumname: restore_##mytypename();break
#define CASE_ENUM_DISPOSE(enumname,mytypename) \
case BITYPE_##enumname: dispose_##mytypename();break
#define CASE_ENUM_SIZEOF(enumname,mytypename) \
case BITYPE_##enumname: return sizeof(mytypename)
| true |
62ff1756d6fe4ccf52c4f61a4fcf998a719f8c9d | C++ | KevinACoder/collection | /exception.cpp | UTF-8 | 1,598 | 3.28125 | 3 | [] | no_license | //
// exception.cpp
// boost_t
//
// Created by KevinLiu on 2018/11/17.
// Copyright © 2018 KevinLiu. All rights reserved.
//
#include <stdio.h>
#include "stddefine.h"
#include <boost/exception/all.hpp>
#include <exception>
/*class cexception1 : public std::exception
{
public:
cexception1(const char *msg, int err):
std::exception(),err_no(err){ }
int get_err_no() const
{ return err_no; }
private:
int err_no;
};*/
//define two types of exception info
typedef boost::error_info<struct tag_err_no, int> err_no;
typedef boost::error_info<struct tag_err_str, string> err_str;
//define an exception class
// use virtual inheritance
struct cexception2:
virtual std::exception,
virtual boost::exception
{ };
struct cexception3
{ };
void exception_demo()
{
using namespace boost;
cout<<"start....."<<endl;
//use self-defined exception class
try{
try {
//throw exception with err no 10
throw cexception2() << err_no(10);
} catch (cexception2 & e) {
//get ptr to exception info
cout << *get_error_info<err_no>(e)<<endl;
cout << e.what() << endl;
//add more info to exception
e << err_str("other info");
throw;
}
}catch(cexception2 &e){
cout<<*get_error_info<err_str>(e)<<endl;
}
cout<<"end....."<<endl;
//wrap exception
try{
throw enable_error_info(cexception3()) << errinfo_errno(11);
}catch(boost::exception &e){
cout<< *get_error_info<errinfo_errno>(e)<<endl;
}
}
| true |
a2099aa174b0f1f3e3dd12c4bee2f947d71873f4 | C++ | dongeronimo/exdental | /teste_algoritmos/RgbToGrayscale/rgbToGrayscale.cpp | UTF-8 | 1,899 | 2.71875 | 3 | [] | no_license | #include <string>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <itkImage.h>
#include <vtkSmartPointer.h>
#include <vtkImageData.h>
#include <vtkPNGReader.h>
using namespace std;
vtkSmartPointer<vtkImageData> LoadImagemOriginal(string filepath);
int main(int argc, char* argv[])
{
string inPath = argv[1];
string outPath = argv[2];
vtkSmartPointer<vtkImageData> input = LoadImagemOriginal(inPath);
typedef itk::Image<unsigned char, 2> ImageType;
ImageType::Pointer itkImage = ImageType::New();
ImageType::RegionType region;
ImageType::IndexType index;
index[0] = 0; index[1] = 0;
region.SetIndex(index);
ImageType::SizeType size;
size[0] = input->GetDimensions()[0];
size[1] = input->GetDimensions()[1];
region.SetSize(size);
itkImage->SetRegions(region);
itkImage->Allocate();
//A passagem tem que ser manual pq o fft exige uma entrada de numeros reais.
unsigned char *sourceBuffer = reinterpret_cast<unsigned char*>(input->GetScalarPointer());
unsigned char *destBuffer = itkImage->GetBufferPointer();
for (auto i = 0; i<size[0] * size[1]; i++)
{
destBuffer[i] = sourceBuffer[i * 3];
}
itk::ImageFileWriter<itk::Image<unsigned char, 2>>::Pointer writer = itk::ImageFileWriter<itk::Image<unsigned char, 2>>::New();
writer->SetInput(itkImage);
writer->SetFileName(outPath.c_str());
try
{
writer->Write();
}
catch(itk::ExceptionObject &ex)
{
cout << ex << endl;
}
return EXIT_SUCCESS;
}
vtkSmartPointer<vtkImageData> LoadImagemOriginal(string filepath)
{
vtkSmartPointer<vtkPNGReader> reader = vtkSmartPointer<vtkPNGReader>::New();
reader->SetFileName(filepath.c_str());
reader->Update();
vtkSmartPointer<vtkImageData> resultado = reader->GetOutput();
cout << "Scalar type: " << resultado->GetScalarTypeAsString() << endl;
cout << "Scalar components: " << resultado->GetNumberOfScalarComponents() << endl;
return resultado;
} | true |
cd13ea5d29331bd92486b6ce963b2d024ad05711 | C++ | RIckyBan/competitive-programming | /AtCoder/PetrozavodskContest/001/C.cpp | UTF-8 | 879 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
#define INF 1e9
#define MAXN 100005
#define MAXM 100005
#define ll long long
#define vi vector<int>
#define vll vector<long long>
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define pii pair<int, int>
string S, l ,r, res;
int N, k, ok, ng, mid;
void solve(){
rep(i, k){
mid = (ok + ng)/ 2;
cout << mid << endl;
cin >> res;
if(res == "Vacant") exit(1);
if(mid%2==0)(res==l ? ok : ng)=mid;
else (res==r ? ok : ng)=mid;
}
}
int main(){
cin >> N;
k = 20;
// 半開区間で管理
ok = 0, ng = N;
cout << 0 << endl;
cin >> l;
if(l == "Vacant") exit(1);
cout << N-1 << endl;
cin >> r;
if(r == "Vacant") exit(1);
k -= 2;
solve();
}
| true |
34349f0d6dbd2a16c1b65a49ba4e9a42af07e8e5 | C++ | IssaMDOunejjaR/Cpp_Modules | /Module 04/ex00/Victim.cpp | UTF-8 | 1,801 | 3.03125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Victim.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: iounejja <iounejja@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/27 13:03:33 by iounejja #+# #+# */
/* Updated: 2021/06/27 18:48:42 by iounejja ### ########.fr */
/* */
/* ************************************************************************** */
#include "Victim.hpp"
Victim::Victim(void)
{
return ;
}
Victim::Victim(std::string name)
{
this->name = name;
std::cout << "Some random victim called " << this->getName() << " just appeared!" << std::endl;
return ;
}
Victim::Victim(Victim & instance)
{
*this = instance;
return ;
}
Victim::~Victim(void)
{
std::cout << "Victim " << this->getName() << " just died for no apparent reason!" << std::endl;
return ;
}
Victim & Victim::operator=(Victim const & instance)
{
this->name = instance.getName();
return (*this);
}
std::ostream & operator<<(std::ostream & output, Victim const & instance)
{
output << "I'm " << instance.getName() << " and I like otters!" << std::endl;
return (output);
}
std::string Victim::getName(void) const
{
return (this->name);
}
void Victim::getPolymorphed(void) const
{
std::cout << this->getName() << " has been turned into a cute little sheep!" << std::endl;
return ;
} | true |
892c2b8c0ee0f9a65a9975418bd84475e75d9523 | C++ | schollz/CISC220-Final-Project | /ChordGraph.cpp | UTF-8 | 2,920 | 3.328125 | 3 | [] | no_license | #include "ChordGraph.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <math.h>
#include <algorithm>
#include <vector>
#include <limits>
#include <string>
#include <sstream>
using namespace std;
// Code that creates a vector of strings using delimiters. Each index of the vector will contain a chord.
void line_populate(vector<string> &record, const string& line, char delimiter) {
int linepos=0;
char c;
int i;
int linemax=line.length();
string curstring;
record.clear();
while(line[linepos]!=0 && linepos < linemax) {
c = line[linepos];
// Skip over text inbetween brackets
if (c=='['){
while (c!=']'){
linepos++;
c = line[linepos];
}
linepos++;
c = line[linepos];
}
// Skip over things that are not chords, and add the current string to the vector (unless empty due to previous delimiter)
if (c==delimiter || c=='|' || c=='.') {
//end of field
if (curstring != ""){
record.push_back( curstring );
curstring="";
}
}
else if ((c=='\r' || c=='\n')) { // End of line
if (curstring != ""){
record.push_back( curstring );
}
return;
}
else { // Is part of chord
curstring.push_back(c);
}
linepos++;
}
if (curstring != ""){
record.push_back( curstring );
}
return;
}
// Code that reads a file of chords, and makes a ChordGraph of it. The file must contain chords separated by spaces or newlines only!
// The very last line of the file will not be read, song information can be stored there.
bool parseChords(ChordGraph & cg, char * fileName){
ifstream inFile(fileName); // Input File Stream
// Error stuff
if (!inFile){
cerr << "Error with opening file" << endl;
return false;
}
if (inFile.fail()) {
cerr << "No file with that name" <<endl;
return false;
}
string line; // Holds the current line from getLine
vector<string> row; // Holds the parsed chords of the current line
string carry = ""; // Holds the chord in the last index of the last row
while (getline(inFile, line, '\n') && inFile.good() ){
line_populate(row, line, ' '); // Read the current line
// If this isn't the first line of the file
if (carry != ""){
// Make a progression from to last chord of the last line to the first chord of this line
//cout << "--------------------" << endl;
cg.addProgression(carry, row[0]);
}
// For every chord except the last in this line
for (int i = 0; i < row.size() - 1; i++){
// Make a progression from first chord to next chord
//cout << "--------------------" << endl;
cg.addProgression(row[i], row[i+1]);
}
// Set the carry chord to the last chord of this line that a progression can be made to the first chord of the next line
carry = row.back();
}
return true;
} | true |
748000fe2edcc19b587883e21b1af9ee4c01ced7 | C++ | NH333/novel | /caq/cppPrimer/ch12/12_23.cpp | UTF-8 | 619 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
int main() {
char* p1 = new char[10]{"anqi"};
char* p2 = new char[10]{"chen"};
int len = strlen(p1) + strlen(p2) + 1;
char* result = new char[len](); //注意初始化,没有初始化为空,后面的strcat就无法进行拼接
char* result2 = new char[len]();
strcat_s(result, len, p1);
strcat_s(result, len, p2);
//strcat_s(result, len, p2);
std::cout << result << std::endl;
std::string s1 = "anqi";
std::string s2 = "chen";
strcpy_s(result, len, (s1 + s2).c_str());
std::cout << result << std::endl;
delete[] result;
system("pause");
} | true |
fca41a9dcf2ae0b8d5991f00a154354c40998b9b | C++ | Meegan1/N-Queen-Parallel | /main.cpp | UTF-8 | 8,384 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <queue>
#include <future>
typedef int chessboard;
template <typename T>
class ThreadSafeQueue {
public:
explicit ThreadSafeQueue() = default;
void push(T &&new_value) {
std::lock_guard<std::mutex> lock(gate);
queue.push(std::move(new_value));
}
bool try_pop(T& val)
{
std::lock_guard<std::mutex> lock(gate);
if (queue.empty()) return false;
val(std::move(queue.front()));
queue.pop();
return true;
}
bool isEmpty() {
std::lock_guard<std::mutex> lock(gate);
return queue.empty();
}
private:
std::queue<T> queue;
std::mutex gate;
};
struct ProblemState {
chessboard ld, cols, rd;
std::promise<int> promise;
explicit ProblemState(chessboard ld, chessboard cols, chessboard rd)
: ld(ld), cols(cols), rd(rd) {}
ProblemState(const ProblemState & other) = delete;
ProblemState(ProblemState && other) : ld(other.ld), cols(other.cols), rd(other.rd), promise(std::move(other.promise)) {}
void operator()(ProblemState && other) {
ld = other.ld;
cols = other.cols;
rd = other.rd;
promise = std::move(other.promise);
}
~ProblemState() = default;
};
class Solver {
public:
/*
* Constructor for Solver
*/
Solver(int n_threads, int n_level) : n_threads(n_threads), start_time(0), end_time(0), n_level(n_level) {
// spawn threads
for (int i = 0; i < n_threads; i++) {
threads.emplace_back(&Solver::wait_and_solve, this); // add thread to vector data structure
if (!threads[i].joinable()) // check thread was created
throw std::logic_error("no thread");
}
}
/*
* Destructor for Solver
*/
~Solver() {
shutdown(); // execute shutdown of threads
time(&end_time); // get end time of algorithm
std::cout << "Total Time Elapsed: " << end_time - start_time << "s" << std::endl; // print out time elapsed
}
/*
* Solve for n queens
*/
void solve(int queens) {
n_queens = queens; // set n-queens
time(&start_time); // get starting time
all = (1 << n_queens) - 1; // set N bits on, representing number of columns
ProblemState problem(0, 0, 0); // create initial problem state
std::shared_future<int> future(problem.promise.get_future()); // get future for initial state
states.push(std::move(problem)); // push state to the queue, triggering threads to solve the problem
std::cout << "Number of Solutions: " << future.get() << std::endl; // get the solution from the future and print to console
}
private:
int n_threads; // n number of threads to spawn
int n_level; // n number of levels until switching to sequential algorithm
int n_queens; // n number of queens to solve for
time_t start_time; // start time of program
time_t end_time; // end time of program
chessboard all;
std::vector<std::thread> threads; // vector of threads
ThreadSafeQueue<ProblemState> states; // queue of problem states
bool m_shutdown; // breaks threads from infinite loop
std::condition_variable m_condition; // conditional variable for when problem state is pushed to queue
std::mutex m_mutex; // mutex for queue
/*
* Starting function for threads to continually solve problems pushed to the queue
*/
void wait_and_solve() {
while(!m_shutdown) { // infinite loop until shutdown request
try_and_solve(); // try and solve a problem state
}
}
/*
* try and solve a problem
*/
void try_and_solve() {
ProblemState state(0, 0, 0); // generate blank temp state
bool success; // create bool for try_pop
{
std::unique_lock<std::mutex> lock(m_mutex); // lock mutex
if(states.isEmpty()) { // if states is empty
m_condition.wait(lock, [this]{return states.isEmpty() || m_shutdown;}); // wait for notification that states isn't empty OR shutdown request
}
success = states.try_pop(state); // try and pop a state from the queue
}
if(success) { // if state successfully pop
solve(std::move(state)); // solve problem state
}
}
/*
* Parallel version of algorithm
*/
void solve(ProblemState &&state) {
if (state.cols == all) { // A solution is found
state.promise.set_value(1); // set value of current problem state to 1
return;
}
chessboard pos = ~(state.ld | state.cols | state.rd) & all; // Possible positions for the queen on the current row
chessboard next;
// get current level of problem
std::bitset<sizeof(chessboard) * CHAR_BIT> b(state.cols);
int level = b.count();
int sol = 0;
// if current remaining levels is less than n_levels argument, run sequentially
if(n_queens - level <= n_level) {
sol += seq_nqueen(state.ld, state.cols, state.rd);
}
else { // else calculate next problem and push to ProblemState queue
std::queue<std::shared_future<int>> futures_queue; // queue of futures
while (pos != 0) { // Iterate over all possible positions and push to states queue
next = pos & (-pos); // next possible position
pos -= next; // update the possible position
ProblemState problem((state.ld | next) << 1, state.cols | next, (state.rd | next) >> 1); // create problem state
futures_queue.emplace(problem.promise.get_future()); // get future of problem state and push to futures queue
states.push(std::move(problem)); // push new problem to queue of problem states
}
// loop through futures queue
while(!futures_queue.empty()) {
// get future
std::shared_future<int> future(futures_queue.front());
futures_queue.pop();
while (future.wait_for(std::chrono::nanoseconds(1)) != std::future_status::ready) { // while future not ready
try_and_solve(); // solve another problem from problem state queue
}
sol += future.get(); // get future when ready and add result to sol
}
}
state.promise.set_value(sol); // set value of promise for current state to sol
}
/*
* Sequential version of algorithm
*/
int seq_nqueen(chessboard ld, chessboard cols, chessboard rd) {
int sol = 0;
if (cols == all) // A solution is found
return 1;
chessboard pos = ~(ld | cols | rd) & all; // Possible posstions for the queen on the current row
chessboard next;
while (pos !=
0) { // Iterate over all possible positions and solve the (N-1)-queen in each case
next = pos & (-pos); // next possible position
pos -= next; // update the possible position
sol += seq_nqueen((ld | next) << 1, cols | next, (rd | next) >> 1); // recursive call for the `next' position
}
return sol;
}
/*
* Shutdown threads
*/
void shutdown() {
// unblock all threads waiting
m_shutdown = true;
m_condition.notify_all();
// loop through threads and join
for (int i = 0; i < n_threads; i++) {
if (threads[i].joinable())
threads[i].join();
}
}
};
int main(int argc, char **argv) {
if (argc < 4) {
std::cout << "You have to provide: \n 1) Number of Queens \n 2) Number of threads \n 3) Number of levels left before switching to sequential" << std::endl;
return 0;
}
int qn = std::stoi(argv[1]); // get n queens
int tn = std::stoi(argv[2]); // get n threads
int ln = std::stoi(argv[3]); // get n levels
Solver solver(tn, ln); // create solver object with n threads and n levels before sequential
solver.solve(qn); // solve for n queens
return 0;
} | true |
727231cc5141e059a2164eee90846ca65b684b0b | C++ | Na5morK/MInDiff | /MInimal difference(минимальная разность).cpp | UTF-8 | 713 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <complex>
//поиск минимальной разности
int main()
{
using namespace std;
//cout<<"инициализация...\n";
int const SIZE=4;
int a[SIZE],min=2147483647;
//cout<<"успешно.\n";
//cout<<"ввод...\n";
cout<<"Enter array\n";
for (int i=0;i<SIZE;i++)
cin>>a[i];
//cout<<"успешно.\n";
//цикл
for (int i=0 ; i<(SIZE-1); i++)
{
for(int j=1; j<SIZE ; j++)
{
if (i!=j)
{
if ((abs(a[i]-a[j]))<min)
min=(abs(a[i]-a[j]));
}
}
}
cout<<"Minimal difference is "<<min;
cout<<"\n";
return 0;
}
| true |
825cecf26068518784a8e061f506c6215bfa1964 | C++ | gitcseme/solved-problems-catagorized | /Math/uva 1636 Headshot.cpp | UTF-8 | 667 | 2.8125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
char ch[105];
int len, a, b, c, d;
void r() {
int cnt = 0;
for (int i = 0; i < len; ++i)
if (ch[i] == '0') ++cnt;
a = cnt;
b = len;
}
void s() {
int cnt = 0;
for (int i = 1; i < len; ++i)
if (ch[i] == '0' && ch[i-1] == '0') ++cnt;
if (ch[0] == '0' && ch[len-1] == '0') ++cnt;
c = cnt;
d = a;
}
int main () {
while (scanf("%s", ch) != EOF) {
len = strlen(ch);
r();
s();
if ( (a * d) > (b * c) ) printf("ROTATE\n");
else if ( (a * d) < (b * c) ) printf("SHOOT\n");
else printf("EQUAL\n");
}
return 0;
}
| true |
a758ed32fd13e0da06bf02ea2726fa697e36449f | C++ | linmx0130/OJCode | /POJ/P2245/main.cpp | UTF-8 | 538 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define MAXN 15
int S[MAXN];
int N;
int PQ[MAXN];
void Search(int now,int last)
{
if (now==7)
{
for (int i=1;i<6;++i)
{
printf("%d ",S[PQ[i]]);
}
printf("%d\n",S[PQ[6]]);
}
for (int i=last+1;i<=N;++i)
{
PQ[now]=i;
Search(now+1,i);
}
}
void Main()
{
for (int i=1;i<=N;++i)
{
scanf("%d",&S[i]);
}
Search(1,0);
}
int main()
{
bool first=1;
while (scanf("%d",&N),N!=0)
{
if (first) first=0;else puts("");
Main();
}
return 0;
}
| true |
2828bde89da1eb2b473c60a14b4aa7db8911f833 | C++ | jeffsetter/coreir | /src/lib/passes/inline.cpp | UTF-8 | 7,282 | 2.90625 | 3 | [] | no_license | #include "coreir-pass/passes.h"
namespace CoreIR {
// This helper will connact everything from wa to wb with a spDelta.
// spDelta is the SelectPath delta to get from wa to wb
void connectOffsetLevel(ModuleDef* def, Wireable* wa, SelectPath spDelta, Wireable* wb) {
//cout << "w:" << w->toString() << endl;
//cout << "spDelta:" << SelectPath2Str(spDelta) << endl;
//cout << "inw:" << inw->toString() << endl << endl;
for (auto waCon : wa->getConnectedWireables() ) {
for (auto wbCon : wb->getConnectedWireables() ) { //was inw
SelectPath wbConSPath = wbCon->getSelectPath();
SelectPath waConSPath = waCon->getSelectPath();
//concatenate the spDelta into wa
waConSPath.insert(waConSPath.end(),spDelta.begin(),spDelta.end());
def->connect(waConSPath,wbConSPath);
//cout << "Hconnecting: " << SelectPath2Str(wOtherSPath) + " <==> " + SelectPath2Str(inwOtherSPath) << endl;
}
}
//Traverse up the wa keeping wb constant
if (auto was = dyn_cast<Select>(wa)) {
SelectPath tu = spDelta;
assert(was->getParent());
tu.insert(tu.begin(),was->getSelStr());
connectOffsetLevel(def,was->getParent(),tu,wb);
}
//Traverse down the wb keeping wa constant
for (auto wbselmap : wb->getSelects()) {
SelectPath td = spDelta;
td.push_back(wbselmap.first);
connectOffsetLevel(def,wa,td,wbselmap.second);
}
}
//This helper will connect a single select layer of the passthrough.
void connectSameLevel(ModuleDef* def, Wireable* wa, Wireable* wb) {
//wa should be the flip type of wb
assert(wa->getType()==wb->getType()->getFlipped());
auto waSelects = wa->getSelects();
auto wbSelects = wb->getSelects();
//Sort into the three sets of the vendiagram
unordered_set<string> waOnly;
unordered_set<string> wbOnly;
unordered_set<string> both;
for (auto waSelmap : waSelects) {
if (wbSelects.count(waSelmap.first)>0) {
both.insert(waSelmap.first);
}
else {
waOnly.insert(waSelmap.first);
}
}
for (auto wbSelmap : wbSelects) {
if (both.count(wbSelmap.first) == 0) {
wbOnly.insert(wbSelmap.first);
}
}
//Basic set theory assertion
assert(waOnly.size() + wbOnly.size() + 2*both.size() == waSelects.size() + wbSelects.size());
//Traverse another level for both
for (auto selstr : both ) {
connectSameLevel(def,waSelects[selstr],wbSelects[selstr]);
}
//TODO check bug here first
//Connect wb to all the subselects of waOnly
for (auto selstr : waOnly) {
connectOffsetLevel(def,wb, {selstr}, waSelects[selstr]);
}
//Connect wa to all the subselects of wbOnly
for (auto selstr : wbOnly) {
connectOffsetLevel(def,wa, {selstr}, wbSelects[selstr]);
}
//Now connect all N^2 possible connections for this level
for (auto waCon : wa->getConnectedWireables() ) {
for (auto wbCon : wb->getConnectedWireables() ) {
def->connect(waCon,wbCon);
//cout << "connecting: " << SelectPath2Str(wOther->getSelectPath()) + " <==> " + SelectPath2Str(inwOtherSPath) << endl;
}
}
}
//addPassthrough will create a passthrough Module for Wireable w with name <name>
//This buffer has interface {"in": Flip(w.Type), "out": w.Type}
// There will be one connection connecting w to name.in, and all the connections
// that originally connected to w connecting to name.out which has the same type as w
Instance* addPassthrough(Context* c, Wireable* w,string instname) {
//First verify if I can actually place a passthrough here
//This means that there can be nothing higher in the select path tha is connected
Wireable* wcheck = w;
while (Select* wchecksel = dyn_cast<Select>(wcheck)) {
Wireable* wcheck = wchecksel->getParent();
ASSERT(wcheck->getConnectedWireables().size()==0,"Cannot add a passthrough to a wireable with connected selparents");
}
ModuleDef* def = w->getModuleDef();
Type* wtype = w->getType();
//Add actual passthrough instance
Instance* pt = def->addInstance(instname,c->getNamespace("stdlib")->getGenerator("passthrough"),{{"type",c->argType(wtype)}});
//Connect all the original connections to the passthrough.
std::function<void(Wireable*)> swapConnections;
swapConnections = [instname,def,&swapConnections](Wireable* curw) ->void {
SelectPath curSP = curw->getSelectPath();
curSP[0] = instname;
curSP.insert(curSP.begin()+1,"out");
for (auto conw : curw->getConnectedWireables()) {
SelectPath conSP = conw->getSelectPath();
def->connect(curSP,conSP);
def->disconnect(curw,conw);
}
for (auto selmap : curw->getSelects()) {
swapConnections(selmap.second);
}
};
swapConnections(w);
//Connect the passthrough back to w
def->connect(w,pt->sel("in"));
w->getModuleDef()->print();
return pt;
}
//This will inline an instance of a passthrough
void inlinePassthrough(Instance* i) {
ModuleDef* def = i->getModuleDef();
//This will recursively connect all the wires together
connectSameLevel(def, i->sel("in"),i->sel("out"));
//Now delete this instance
def->removeInstance(i);
}
//This will modify the moduledef to inline the instance
void inlineInstance(Instance* inst) {
ModuleDef* def = inst->getModuleDef();
Module* modInline = inst->getModuleRef();
//Special case for a passthrough
if (inst->isGen() && inst->getGeneratorRef()->getName() == "passthrough") {
inlinePassthrough(inst);
return;
}
if (!modInline->hasDef()) {
cout << "Cannot inline a module with no definition!: " << modInline->getName() << endl;
return;
}
//I will be inlining defInline into def
//Making a copy because i want to modify it first without modifying all of the other instnaces of modInline
ModuleDef* defInline = modInline->getDef()->copy();
Context* c = modInline->getContext();
//Add a passthrough Module to quarentine 'self'
addPassthrough(c,defInline->getInterface(),"_insidePT");
string inlinePrefix = inst->getInstname() + "$";
//First add all the instances of defInline into def with a new name
for (auto instmap : defInline->getInstances()) {
string iname = inlinePrefix + instmap.first;
def->addInstance(instmap.second,iname);
}
//Now add all the easy connections (that do not touch the boundary)
for (auto cons : defInline->getConnections()) {
SelectPath pA = cons.first->getSelectPath();
SelectPath pB = cons.second->getSelectPath();
//Easy case: when neither are connect to self
if (pA[0] != "self" && pB[0] != "self") {
//Create the correct names and connect
pA[0] = inlinePrefix + pA[0];
pB[0] = inlinePrefix + pB[0];
def->connect(pA,pB);
}
}
//Create t3e Passthrough to quarentene the instance itself
Instance* outsidePT = addPassthrough(c,inst,"_outsidePT");
//Connect the two passthrough buffers together ('in' ports are facing the boundary)
def->connect("_outsidePT.in",inlinePrefix + "_insidePT.in");
//Now remove the instance (which will remove all the previous connections)
def->removeInstance(inst);
//Now inline both of the passthroughs
inlineInstance(outsidePT);
inlineInstance(cast<Instance>(def->sel(inlinePrefix + "_insidePT")));
//typecheck the module
def->validate();
}
}
| true |
015375e0c73bafe2d391714c0869d680bc5e1413 | C++ | ashishugi/MYCODES | /strings/naivematch.cpp | UTF-8 | 483 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool ismatch(string s,string p){
bool check = true;
for(int i=0;i<(s.length() - p.length());i++){
check = true;
for(int j=0;j<(p.length());j++){
if(s[i+j]!=p[j]){
check= false;
break;
}
}
if(check){
return true;
}
}
return false;
}
int main(void){
string s,p;
cin>>s;
cin>>p;
cout<<ismatch(s,p)<<endl;
} | true |
034ddcec52d3055c84278e9dfd4043260d2b4c63 | C++ | LeonAbelmann/MagOD | /Testfunctions/MagOD2/TestLED/TestLED.ino | UTF-8 | 1,450 | 3.34375 | 3 | [
"MIT"
] | permissive | //Pins for the RGB LED.
#define LED_red 2 //RED LED
#define LED_green 32 //Green LED
#define LED_blue 4 //BLUE LED
/* Coil variables (to switch them off) */
uint8_t Coil_x = 33; // output of the coils in the x direction
uint8_t Coil_y = 26; // output of the coils in the y direction
uint8_t Coil_z = 14; // output of the coils in the z direction
const int ledChannel_x = 3; /*0-15*/
const int ledChannel_y = 4; /*0-15*/
const int ledChannel_z = 5; /*0-15*/
void setup () {
//Switch off the magnets:
ledcSetup(ledChannel_x, 1000, 8);
ledcSetup(ledChannel_y, 1000, 8);
ledcSetup(ledChannel_z, 1000, 8);
ledcAttachPin(Coil_x, ledChannel_x);
ledcAttachPin(Coil_y, ledChannel_y);
ledcAttachPin(Coil_z, ledChannel_z);
ledcWrite(ledChannel_x, 0);
ledcWrite(ledChannel_y, 0);
ledcWrite(ledChannel_z, 0);
// set the LEDs
pinMode(LED_red, OUTPUT);
pinMode(LED_green, OUTPUT);
pinMode(LED_blue, OUTPUT);
}
void loop()
{
/* Cycle through RED, GREEN, BLUE, PAUZE for 1 sec each */
digitalWrite(LED_red, HIGH);
digitalWrite(LED_green, LOW);
digitalWrite(LED_blue, LOW);
delay(1000);
digitalWrite(LED_red, LOW);
digitalWrite(LED_green, HIGH);
digitalWrite(LED_blue, LOW);
delay(1000);
digitalWrite(LED_red, LOW);
digitalWrite(LED_green, LOW);
digitalWrite(LED_blue, HIGH);
delay(1000);
digitalWrite(LED_red, LOW);
digitalWrite(LED_green, LOW);
digitalWrite(LED_blue, LOW);
delay(1000);
}
| true |
7da438fd68bffedc866f116c26c98fc3b678d474 | C++ | ksercs/algo_school_base | /base/Работа с файлами. Ввод-вывод/Задача 2/Task 2.cpp | MacCyrillic | 448 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int ans,num;
int main()
{
ifstream cin("Task 2.in");
ofstream cout ("Task 2.out");
//cout <<"\n ";
cin >>num;
ans=(num%1000)/100;
cout /*<<"\n "*/ <<ans;
getch ();
return 0;
}
| true |
7ded95f2383005a02809be9ec0a9e36a36466214 | C++ | nikhil-seth/LeetCode | /876. Middle of the Linked List.cpp | UTF-8 | 511 | 3.4375 | 3 | [] | no_license | //876. Middle of the Linked List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(!head)
return head;
ListNode *p,*c;
p=c=head;
while(p->next!=nullptr){
c=c->next;
p=p->next;
if(p->next)
p=p->next;
}
return c;
}
}; | true |
9954dad66689a2faa45fd20e6e5ee5ca91a39ce7 | C++ | PRKKILLER/Algorithm_Practice | /LeetCode/0009-Palindrome Number/main.cpp | UTF-8 | 1,296 | 3.84375 | 4 | [] | no_license | //
// Created by 薛智钧 on 2020/3/16.
//
// Determine whether an integer is a palindrome.
// An integer is a palindrome when it reads the same backward as forward.
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
public:
// 利用string
bool isPalindrome(int x) {
string strNum = to_string(x);
auto i = strNum.begin(), j = strNum.end() - 1;
while (i != j){
if (*i != *j) return false;
if (i + 1 == j) return true;
++i; --j;
}
return true;
}
// 不利用string
// 首先获得x的位数,然后依次比较最高位和最低位
bool isPalindrome_2(int x){
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int div = 1;
while (x / div >= 10) div *= 10; // div存储x的位数
while (x > 0){
int lo = x % 10;
int hi = x / div;
if (lo != hi) return false;
// x%div 可将数字最高位舍去
// (x%div) / 10 可将数字最低位舍去
x = (x % div) / 10; // 去除数字的最高两位
div /= 100;
}
return true;
}
};
int main(){
int num = 11;
Solution sol;
cout<<sol.isPalindrome_2(num);
}
| true |
2a1364587650ecee8613f11d5c1e953c2ee0b1e8 | C++ | plasma-effect/For_My_Game | /plasma/range_number.hpp | UTF-8 | 786 | 2.578125 | 3 | [
"BSL-1.0"
] | permissive | // Copyright plasma-effect 2014.
// 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)
#pragma once
#include<plasma/config.hpp>
namespace plasma
{
template<class T,T Min,T Max>class range_number
{
static_assert(Min<=Max,"template parameter Min must be less than Max");
T value_;
public:
static PLASMA_SWITCH_CONSTEXPR T min = Min;
static PLASMA_SWITCH_CONSTEXPR T max = Max;
typedef T value_type;
typedef range_number<T,Min,Max> type;
PLASMA_CONSTEXPR range_number(T v = T()):
value_((v < Min ? Min :(v > Max ? Max : v))){}
PLASMA_CONSTEXPR range_number(type const& v):
value_(v.value_){}
PLASMA_CONSTEXPR operator T()const{return value_;}
};
}
| true |
96a20cbe1d46890b7e5d7b6485127c693c5d6314 | C++ | FancyKings/SDUSTOJ_ACCode | /Code_by_runid/2329815.cc | UTF-8 | 1,268 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#define timespec A_A_A
#include <iomanip>
typedef long long LL;
using namespace std;
stack<double> num;
stack<char> all;
int main(int argc, char const *argv[])
{
std::ios::sync_with_stdio(false);
int n;
while (cin >> n)
{
double dig;
char sign;
while (n--)
{
cin >> dig >> sign;
if (!all.empty())
{
if (all.top() == '-')
dig = -dig;
else if (all.top() == '*')
{
dig *= num.top();
num.pop();
}
else if (all.top() == '/')
{
dig /= num.top();
num.pop();
}
}
num.push(dig);
all.push(sign);
}
double ans = 0;
while (!num.empty())
{
ans += num.top();
num.pop();
}
while (!all.empty())
{
all.pop();
}
cout << setiosflags(ios::fixed) << setprecision(2) << ans << endl;
}
return 0;
}
/**************************************************************
Problem: 1351
User: 201701060705
Language: C++
Result: Accepted
Time:0 ms
Memory:1280 kb
****************************************************************/
| true |
6dff7a6b624a498dd88afdd62d3a85bd339cd5e5 | C++ | LangeraertPepijn/Minigin | /Minigin/Observer.h | UTF-8 | 446 | 2.609375 | 3 | [] | no_license | #pragma once
#include "GameObject.h"
#include "Event.h"
class Observer
{
public:
Observer() = default;
Observer(const Observer& other) = delete;
Observer(Observer&& other) = delete;
Observer& operator=(const Observer& other) = delete;
Observer& operator=(Observer&& other) = delete;
virtual ~Observer() = default;
virtual void Notify(const std::shared_ptr<GameObject> actor, Event event,const std::weak_ptr<GameObject> parent) = 0;
};
| true |
962a298d7c6b8a1794d00aa31245565a551d27f8 | C++ | denis-gubar/Leetcode | /Hash Table/2461. Maximum Sum of Distinct Subarrays With Length K.cpp | UTF-8 | 803 | 2.546875 | 3 | [] | no_license | class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
long long result = 0;
int N = nums.size();
unordered_map<int, int> M;
int nonDistinct = 0;
long long sum = 0;
for (int i = 0; i < k; ++i)
{
if (++M[nums[i]] == 2)
++nonDistinct;
sum += nums[i];
}
if (nonDistinct == 0)
result = sum;
for (int i = k; i < N; ++i)
{
sum -= nums[i - k];
sum += nums[i];
if (--M[nums[i - k]] == 1)
--nonDistinct;
if (++M[nums[i]] == 2)
++nonDistinct;
if (nonDistinct == 0)
result = max(result, sum);
}
return result;
}
};
| true |
f2a8d8d0243e8e7ab5bd2dcdf417c7bb410150be | C++ | guptapiyush8871/BasicRayTracer | /RenderConfig.cpp | UTF-8 | 1,511 | 2.6875 | 3 | [] | no_license | #include "RenderConfig.h"
RenderConfig::RenderConfig() :
m_Msaa(e1X),
m_BackgroundColor(RGBAColor())
{
}
RenderConfig::~RenderConfig()
{
}
void RenderConfig::SetBackgroundColor(const RGBAColor& iBackgroundColor)
{
m_BackgroundColor = iBackgroundColor;
}
RGBAColor RenderConfig::GetBackgroundColor() const
{
return m_BackgroundColor;
}
void RenderConfig::SetMSAA(const EMSAA iMsaa)
{
m_Msaa = iMsaa;
}
RenderConfig::EMSAA RenderConfig::GetMSAA() const
{
return m_Msaa;
}
std::vector<std::pair<float, float> > RenderConfig::GetSampleLocations(EMSAA iMsaa) const
{
std::vector<std::pair<float, float> > samplePositions;
int row = 1;
int col = 1;
float startX = 0.5f;
float startY = 0.5f;
float spanX = 0.0f;
float spanY = 0.0f;
switch (iMsaa)
{
case e1X:
break;
case e2X:
col = 2;
startX = 0.25f;
spanX = 0.5f;
break;
case e4X:
row = 2;
col = 2;
startX = 0.25f;
startY = 0.25f;
spanX = 0.5f;
spanY = 0.5f;
break;
case e8X:
row = 2;
col = 4;
startX = 0.125f;
startY = 0.25f;
spanX = 0.25f;
spanY = 0.5f;
break;
case e16X:
row = 4;
col = 4;
startX = 0.125f;
startY = 0.125f;
spanX = 0.25f;
spanY = 0.25f;
break;
default:
break;
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
samplePositions.push_back(std::pair<float, float>(startX + j*spanX, startY + i*spanY));
}
}
return samplePositions;
}
| true |
97aece57286f3dd270619d37c84f011a33c2563a | C++ | amb-lucas/Competitive-Programming | /Strings/Manacher.cpp | UTF-8 | 747 | 3.46875 | 3 | [] | no_license |
vector<int> findOdd(string &str){
int n = str.size();
vector<int> d1(n);
for(int i=0, l=0, r=-1, k; i<n; i++){
if(i>r) k = 1;
else k = min(d1[l+r-i], r-i+1);
while(0 <= i-k && i+k < n && str[i-k] == str[i+k]) k++;
d1[i] = k--;
if(i+k > r){
l = i-k;
r = i+k;
}
}
return d1;
}
vector<int> findEven(string &str){
int n = str.size();
vector<int> d2(n);
for(int i=0, l=0, r=-1, k; i<n; i++){
if(i > r) k = 0;
else k = min(d2[l+r-i+1], r-i+1);
while(0 <= i-k-1 && i+k < n && str[i-k-1] == str[i+k]) k++;
d2[i] = k--;
if(i+k > r){
l = i-k-1;
r = i+k;
}
}
return d2;
}
| true |
47aaa7f2070aa73f34a5772fccd6ad2c66643ea5 | C++ | rubi1993/SwitchesNRouters | /rules.h | UTF-8 | 2,664 | 2.765625 | 3 | [] | no_license | //
// Created by igor.a on 8/30/18.
//
#ifndef SRA_RULES_H
#define SRA_RULES_H
#include <string>
class Rule{
public:
std::string way_to_rule;
std::string source_address;
std::string destination_address;
int source_adress_start,source_adress_end;
int destination_adress_start,destination_adress_end;
int source_port_start, source_port_end;
int destination_port_start, destination_port_end;
std::string protocol;
int priority;
std::string rule_name;
int num_of_partitions_colliding(int partSize);
Rule(std::string sa, std::string da, int sp_s, int sp_e, int dp_s, int dp_e, std::string p, int pri, std::string name,int sas=0,int sae=0,int das=0,int dae=0):
source_address(sa),
destination_address(da),
source_port_start(sp_s),
source_port_end(sp_e),
destination_port_start(dp_s),
destination_port_end(dp_e),
protocol(p),
priority(pri),
rule_name(name),
source_adress_start(sas),
source_adress_end(sae),
destination_adress_start(das),
destination_adress_end(dae)
{}
Rule(const Rule* rule):source_address(rule->source_address),destination_address
(rule->destination_address),
source_port_start(rule->source_port_start),
source_port_end(rule->source_port_end),
destination_port_start(rule->destination_port_start),
destination_port_end(rule->destination_port_end),
protocol(rule->protocol),
priority(rule->priority),
rule_name(rule->rule_name),
source_adress_start(rule->source_adress_start),
source_adress_end(rule->source_adress_end),
destination_adress_start(rule->destination_adress_start),
destination_adress_end(rule->destination_adress_end)
{}
bool operator!=(const Rule& a) ;
};
class PacketHeader{
public:
std::string source_address;
std::string destination_address;
int source_port;
int destination_port;
std::string protocol;
PacketHeader(std::string sa, std::string da, int sp, int dp, std::string p):source_address(sa),
destination_address(da),
source_port(sp),
destination_port(dp),
protocol(p)
{}
};
#endif //SRA_RULES_H
| true |
13c001af0d9cdbf8587a29d3133b00f37a5df824 | C++ | jasonmnemonic/qfx-analysis | /src/StochMATrendGroup.cpp | UTF-8 | 1,586 | 2.703125 | 3 | [] | no_license | #include "StochMATrendGroup.hpp"
#include "Stochastic.hpp"
#include "MovingAverageTrend.hpp"
StochMATrendGroup::StochMATrendGroup(Parser *parser) {
mas = {
new MovingAverageTrend(parser, false, 10, 25, 50),
new MovingAverageTrend(parser, false, 25, 50, 100),
new MovingAverageTrend(parser, false, 50, 100, 200),
new MovingAverageTrend(parser, false, 100, 200, 400),
};
stochs = {
new Stochastic(parser, 5, 95, 14, 3, 3, true),
new Stochastic(parser, 10, 90, 14, 3, 3, true),
new Stochastic(parser, 15, 85, 14, 3, 3, true),
new Stochastic(parser, 20, 80, 14, 3, 3, true),
new Stochastic(parser, 5, 95, 9, 3, 3, true),
new Stochastic(parser, 10, 90, 9, 3, 3, true),
new Stochastic(parser, 15, 85, 9, 3, 3, true),
new Stochastic(parser, 20, 80, 9, 3, 3, true),
new Stochastic(parser, 5, 95, 5, 3, 3, true),
new Stochastic(parser, 10, 90, 5, 3, 3, true),
new Stochastic(parser, 15, 85, 5, 3, 3, true),
new Stochastic(parser, 20, 80, 5, 3, 3, true),
};
// moving average + stochastic combos
for (auto ma = mas.begin(); ma != mas.end(); ma++) {
for (unsigned int i = 0; i < stochs.size(); i++) {
indicator_groups.push_back(new vector<AbstractIndicator*>{ *ma, stochs[i] });
}
}
// pure stochastic
for (auto stoch = stochs.begin(); stoch != stochs.end(); stoch++) {
indicator_groups.push_back(new vector<AbstractIndicator*>{ *stoch });
}
}
StochMATrendGroup::~StochMATrendGroup() {
// delete indicators
for (auto it = mas.begin(); it != mas.end(); it++) delete *it;
for (auto it = stochs.begin(); it != stochs.end(); it++) delete *it;
}
| true |
50545c8a457608167269803968c0ac4279875de1 | C++ | lys8325/boj_study | /01546/main.cpp | UTF-8 | 313 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, sum=0, tmp, maxN = -1;
double ans;
cin>>n;
for(int i=0;i<n;++i){
cin>>tmp;
maxN = max(maxN, tmp);
sum += tmp;
}
ans = (double)sum * 100 / maxN / n;
cout<<ans;
return 0;
}
| true |
11722985d677edaac50f44c9104e9c4ef9c34dc0 | C++ | jhinkoo331/leetcode | /solution/0021____Merge_Two_Sorted_Lists.cpp | UTF-8 | 564 | 3.375 | 3 | [
"MIT"
] | permissive | #include "model\ListNode.h"
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
return _1(l1, l2);
}
private:
ListNode* _1(ListNode* l1, ListNode* l2){
ListNode head; //* head is initialized in stack
ListNode* tail = &head;
while(l1 != nullptr && l2 != nullptr)
if(l1->val <= l2->val){
tail->next = l1;
l1 = l1->next;
tail = tail->next;
}else{
tail->next = l2;
l2 = l2->next;
tail = tail->next;
}
if(l1 != nullptr)
tail->next = l1;
else
tail->next = l2;
return head.next;
}
};
| true |
c16fc5cc337c38c1a2a06ba9028076a1c3dce849 | C++ | cnsuhao/GUILib-3 | /Slider.cpp | UTF-8 | 3,970 | 2.59375 | 3 | [] | no_license | #include "Slider.h"
Slider::Slider(uint16_t _posX, uint16_t _posY, uint8_t _zDepth, SliderOrientation_t _orientation, uint16_t _length)
{
posX = _posX;
posY = _posY;
zDepth = _zDepth;
orientation = _orientation;
length = _length;
value = 0;
prev_value = 0;
hasTouchEventCallback = false;
invalid = true;
}
void Slider::initialize(void)
{
if(orientation == VERTICAL)
{
width = SLIDER_HANDLE_HEIGHT;
height = length + SLIDER_HANDLE_WIDTH;
}
else
{
height = SLIDER_HANDLE_HEIGHT;
width = length + SLIDER_HANDLE_WIDTH;
}
}
bool Slider::checkBounds(int16_t touchX, int16_t touchY)
{
return true;
}
void Slider::injectTouch(int16_t touchX, int16_t touchY, TouchType_e touchType)
{
GUIElement::injectTouch(touchX, touchY, touchType);
invalid = true;
if(orientation == VERTICAL)
{
value = constrain(length - touchY + SLIDER_HANDLE_WIDTH/2, 0, length);
}
else
{
value = constrain(touchX - SLIDER_HANDLE_WIDTH/2, 0, length);
}
if(hasTouchEventCallback)
onTouchCallback();
}
void Slider::draw(bool clearBeforeDraw)
{
if(clearBeforeDraw)
{
guiController->screen->setPenSolid();
guiController->screen->dRectangle(posX, posY, width, height, SLIDER_BACKGROUND_COLOR);
guiController->screen->setPenSolid(false);
}
// else
// {
// guiController->screen->setPenSolid(true);
// if(orientation == VERTICAL)
// {
//
// guiController->screen->dRectangle(posX, posY + length - prev_value, SLIDER_HANDLE_HEIGHT, SLIDER_HANDLE_WIDTH, SLIDER_BACKGROUND_COLOR);
// guiController->screen->dLine(posX + ((width - SLIDER_LINE_THICKNESS)/2), posY + length - prev_value, 0, SLIDER_HANDLE_WIDTH, SLIDER_LINE_COLOR);
// guiController->screen->dLine(posX + ((width + SLIDER_LINE_THICKNESS)/2), posY + length - prev_value, 0, SLIDER_HANDLE_WIDTH, SLIDER_LINE_COLOR);
// }
// else
// {
// guiController->screen->dRectangle(posX + prev_value, posY, SLIDER_HANDLE_WIDTH, SLIDER_HANDLE_HEIGHT, SLIDER_BACKGROUND_COLOR);
// guiController->screen->dLine(posX + prev_value, posY + ((height - SLIDER_LINE_THICKNESS)/2), SLIDER_HANDLE_WIDTH, 0, SLIDER_LINE_COLOR);
// guiController->screen->dLine(posX + prev_value, posY + ((height + SLIDER_LINE_THICKNESS)/2), SLIDER_HANDLE_WIDTH, 0, SLIDER_LINE_COLOR);
// }
// guiController->screen->setPenSolid(false);
// }
if(orientation == VERTICAL)
{
guiController->screen->dRectangle(posX + (width-SLIDER_LINE_THICKNESS)/2, posY + (height-length)/2, SLIDER_LINE_THICKNESS, length, SLIDER_LINE_COLOR);
guiController->screen->setPenSolid();
guiController->screen->dRectangle(posX, posY + length - value, SLIDER_HANDLE_HEIGHT, SLIDER_HANDLE_WIDTH, SLIDER_HANDLE_COLOR);
guiController->screen->setPenSolid(false);
}
else
{
guiController->screen->dRectangle(posX + (width-length)/2, posY + (height-SLIDER_LINE_THICKNESS)/2, length, SLIDER_LINE_THICKNESS, SLIDER_LINE_COLOR);
guiController->screen->setPenSolid();
guiController->screen->dRectangle(posX + value, posY, SLIDER_HANDLE_WIDTH, SLIDER_HANDLE_HEIGHT, SLIDER_HANDLE_COLOR);
guiController->screen->setPenSolid(false);
}
prev_value = value;
invalid = false;
}
void Slider::registerTouchEventCallback(void (*_onTouchCallback)(void))
{
hasTouchEventCallback = true;
onTouchCallback = _onTouchCallback;
}
uint16_t Slider::getWidth(void)
{
return width;
}
uint16_t Slider::getHeight(void)
{
return height;
}
uint16_t Slider::getPosX(void)
{
return posX;
}
uint16_t Slider::getPosY(void)
{
return posY;
}
uint16_t Slider::getValue(void)
{
return value;
}
void Slider::setValue(uint16_t _value)
{
invalid = true;
value = constrain(_value, 0, length);
}
| true |
d56cc8078446a613186d4a121c1bcf6859d13038 | C++ | borisborgobello/photon-mapping | /src_parallel/raytracing/photon_map.hpp | UTF-8 | 1,944 | 2.6875 | 3 | [] | no_license | #ifndef PHOTON_MAP_HPP_
#define PHOTON_MAP_HPP_
#include <vector>
#include <cstdlib>
#include <boost/shared_ptr.hpp>
#define LIBSSRCKDTREE_HAVE_BOOST
#include <ssrc/spatial/kd_tree.h>
#include "launchables/photon.hpp"
class PhotonMap
{
typedef std::array<double, 3> ArrayPoint ;
typedef ssrc::spatial::kd_tree< ArrayPoint, boost::shared_ptr<Photon> > Tree;
public:
PhotonMap(std::vector< boost::shared_ptr<Photon> > list)
{
for(std::vector< boost::shared_ptr<Photon> >::iterator it = list.begin() ; it != list.end() ; it++)
{
const Point3D& point3d = (*it)->get_end_point() ;
ArrayPoint array_point ;
array_point[0] = point3d[0] ;
array_point[1] = point3d[1] ;
array_point[2] = point3d[2] ;
_map[array_point] = (*it) ;
}
std::cout << "Balancing the photon KD-Tree..." << std::endl ;
_map.optimize() ;
std::cout << "Optimization done." << std::endl ;
}
std::vector< boost::shared_ptr<Photon> > get_k_nearest(const Point3D& point, int k )
{
std::vector< boost::shared_ptr<Photon> > ret ;
ret.clear() ;
if( k <= 0 )
{
for(Tree::iterator it = _map.begin() ; it != _map.end() ; it++)
ret.push_back(it->second) ;
return ret ;
}
Tree::knn_iterator iter_debut, iter_fin ;
ArrayPoint array_point ;
array_point[0] = point[0] ;
array_point[1] = point[1] ;
array_point[2] = point[2] ;
std::pair<Tree::knn_iterator,Tree::knn_iterator> iters =
_map.find_nearest_neighbors(array_point, 1000) ;
for(Tree::knn_iterator it = iters.first ; it != iters.second ; it++)
ret.push_back( it->second ) ;
return ret ;
}
void optimize()
{
_map.optimize() ;
}
private:
Tree _map ;
} ;
#endif // PHOTON_MAP_HPP_
| true |
66a3fd8f4eb9ed204071cb98a0508e4d12a2d41d | C++ | atrin-hojjat/CompetetiveProgramingCodes | /CF/Goodbye 2019/G.cpp | UTF-8 | 1,487 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
const int MaxN = 1e6 + 6.66;
int mark[MaxN];
int arr[MaxN];
vector<int> topo, loop;
void topo_dfs(int v) {
mark[v] = 1;
int u = v - arr[v];
if(mark[u] == 0) topo_dfs(u);
topo.push_back(v);
}
int find_dfs(int v) {
mark[v] = 1;
{
int u = v - arr[v];
if(mark[u] == 2) return -1;
if(mark[u] == 1) {
loop.push_back(u);
return u;
}
int t = find_dfs(u);
if(t == v) {
loop.push_back(u);
return 0;
}
if(t > 0) {
loop.push_back(u);
return t;
}
if(t == 0) return 0;
}
mark[v] = 2;
return -1;
}
#define endl "\n"
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
int t; cin >> t;
while(t--) {
int n; cin >> n;
for(int i = 0; i < n; i++) cin >> arr[i];
bool done = false;
for(int i = 0; i < n; i++)
if(arr[i] == 0) {
cout << 1 << endl << i + 1 << endl;
done = true;
break;
}
if(done) continue;
for(int i = 0; i < n; i++)
if(mark[i] == 0) topo_dfs(i);
for(int i = 0; i < n; i++) mark[i] = 0;
for(auto i : topo)
if(mark[i] == 0) {
int v = find_dfs(i);
if(v == 0) {
cout << loop.size() << endl;
for(auto u : loop)
cout << u + 1 << " "; cout << endl;
break;
}
}
topo.clear();
loop.clear();
for(int i = 0; i <= n; i++) mark[i] = 0;
}
return 0;
}
| true |
a817e2125dcb8a98e55253e25a345fdeb829bacb | C++ | nguyenviettien13/CodeLearning | /1000CppExercise/ACOAlgorithm/antalRank.cpp | UTF-8 | 6,920 | 2.53125 | 3 | [] | no_license | //ACO - Rank based ACO
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <stdio.h>
#include <fstream>
//#include <cv.h>
//#include <highgui.h>
#define MAX_CITIES 30
#define MAX_DIST 100
#define MAX_TOUR (MAX_CITIES * MAX_DIST)
#define MAX_ANTS 30
using namespace std;
//Initial Definiton of the problem
struct cityType{
int x,y;
};
struct antType{
int curCity, nextCity, pathIndex;
int tabu[MAX_CITIES];
int path[MAX_CITIES];
double tourLength;
};
//Ant algorithm problem parameters
#define ALPHA 1.0
#define BETA 5.0 //This parameter raises the weight of distance over pheromone
#define RHO 0.5 //Evapouration rate
#define QVAL 100
#define MAX_TOURS 20
#define MAX_TIME (MAX_TOURS * MAX_CITIES)
#define INIT_PHER (1.0/MAX_CITIES)
#define RANK_W MAX_ANTS/2.0
//runtime Structures and global variables
cityType cities[MAX_CITIES];
antType ants[MAX_ANTS];
antType rankAnts[MAX_ANTS];
double dist[MAX_CITIES][MAX_CITIES];
double phero[MAX_CITIES][MAX_CITIES];
double best=(double)MAX_TOUR;
int bestIndex;
//function init() - initializes the entire graph
void init()
{
int from,to,ant;
ifstream f1;
f1.open("TSP.txt");
//reading TSP
for(from = 0; from < MAX_CITIES; from++)
{
//randomly place cities
f1>>cities[from].x;
f1>>cities[from].y;
cout<<cities[from].x<<" "<<cities[from].y<<endl;
//cities[from].y = rand()%MAX_DIST;
//printf("\n %d %d",cities[from].x, cities[from].y);
for(to=0;to<MAX_CITIES;to++)
{
dist[from][to] = 0.0;
phero[from][to] = INIT_PHER;
}
}
//computing distance
for(from = 0; from < MAX_CITIES; from++)
{
for( to =0; to < MAX_CITIES; to++)
{
if(to!=from && dist[from][to]==0.0)
{
int xd = pow( abs(cities[from].x - cities[to].x), 2);
int yd = pow( abs(cities[from].y - cities[to].y), 2);
dist[from][to] = sqrt(xd + yd);
dist[to][from] = dist[from][to];
}
}
}
//initializing the ANTs
to = 0;
for( ant = 0; ant < MAX_ANTS; ant++)
{
if(to == MAX_CITIES)
to=0;
ants[ant].curCity = to++;
for(from = 0; from < MAX_CITIES; from++)
{
ants[ant].tabu[from] = 0;
ants[ant].path[from] = -1;
}
ants[ant].pathIndex = 1;
ants[ant].path[0] = ants[ant].curCity;
ants[ant].nextCity = -1;
ants[ant].tourLength = 0;
//loading first city into tabu list
ants[ant].tabu[ants[ant].curCity] =1;
}
}
//reinitialize all ants and redistribute them
void restartAnts()
{
int ant,i,to=0;
for(ant = 0; ant<MAX_ANTS; ant++)
{
if(ants[ant].tourLength < best)
{
best = ants[ant].tourLength;
bestIndex = ant;
}
ants[ant].nextCity = -1;
ants[ant].tourLength = 0.0;
for(i=0;i<MAX_CITIES;i++)
{
ants[ant].tabu[i] = 0;
ants[ant].path[i] = -1;
}
if(to == MAX_CITIES)
to=0;
ants[ant].curCity = to++;
ants[ant].pathIndex = 1;
ants[ant].path[0] = ants[ant].curCity;
ants[ant].tabu[ants[ant].curCity] = 1;
}
}
double antProduct(int from, int to)
{
return(( pow( phero[from][to], ALPHA) * pow( (1.0/ dist[from][to]), BETA)));
}
int selectNextCity( int ant )
{
int from, to;
double denom = 0.0;
from=ants[ant].curCity;
for(to=0;to<MAX_CITIES;to++)
{
if(ants[ant].tabu[to] == 0)
{
denom += antProduct( from, to );
}
}
assert(denom != 0.0);
do
{
double p;
to++;
if(to >= MAX_CITIES)
to=0;
if(ants[ant].tabu[to] == 0)
{
p = antProduct(from,to)/denom;
//printf("\n%lf %lf", (double)rand()/RAND_MAX,p);
double x = ((double)rand()/RAND_MAX);
if(x < p)
{
//printf("%lf %lf Yo!",p,x);
break;
}
}
}while(1);
return to;
}
int simulateAnts()
{
int k;
int moving = 0;
for(k=0; k<MAX_ANTS; k++)
{
//checking if there are any more cities to visit
if( ants[k].pathIndex < MAX_CITIES )
{
ants[k].nextCity = selectNextCity(k);
ants[k].tabu[ants[k].nextCity] = 1;
ants[k].path[ants[k].pathIndex++] = ants[k].nextCity;
ants[k].tourLength += dist[ants[k].curCity][ants[k].nextCity];
//handle last case->last city to first
if(ants[k].pathIndex == MAX_CITIES)
{
ants[k].tourLength += dist[ants[k].path[MAX_CITIES -1]][ants[k].path[0]];
}
ants[k].curCity = ants[k].nextCity;
moving++;
}
}
return moving;
}
void sortAnts()
{
antType tempAnt;
int ant,i,j;
for(i=0;i<MAX_CITIES;i++)
{
rankAnts[i] = ants[i];
}
//sorting ants by tour length
for(i=0;i<MAX_CITIES;i++)
{
for(j=i+1;j<MAX_CITIES;j++)
{
if(rankAnts[i].tourLength >= rankAnts[j].tourLength)
{
tempAnt = rankAnts[i];
rankAnts[i] = rankAnts[j];
rankAnts[j] = tempAnt;
}
}
}
}
//Updating trails
void updateTrails()
{
int from,to,i,ant;
//Pheromone Evaporation
for(from=0; from<MAX_CITIES;from++)
{
for(to=0;to<MAX_CITIES;to++)
{
if(from!=to)
{
phero[from][to] *=( 1.0 - RHO);
if(phero[from][to]<0.0)
{
phero[from][to] = INIT_PHER;
}
}
}
}
//Add new pheromone to the trails
for(ant=0;ant<RANK_W-1;ant++)
{
for(i=0;i<MAX_CITIES;i++)
{
if( i < MAX_CITIES-1 )
{
from = rankAnts[ant].path[i];
to = rankAnts[ant].path[i+1];
}
else
{
from = rankAnts[ant].path[i];
to = rankAnts[ant].path[0];
}
phero[from][to] +=(RANK_W - ant)*(QVAL/ rankAnts[ant].tourLength) ; //For rank based updation
phero[to][from] = phero[from][to];
}
}
//Adding the best path
for(i = 0;i<MAX_CITIES;i++)
{
if( i < MAX_CITIES-1 )
{
from = ants[bestIndex].path[i];
to = ants[bestIndex].path[i+1];
}
else
{
from = ants[bestIndex].path[i];
to = ants[bestIndex].path[0];
}
phero[from][to] +=(QVAL/ best) ;
phero[to][from] = phero[from][to];
}
for (from=0; from < MAX_CITIES;from++)
{
for( to=0; to<MAX_CITIES; to++)
{
phero[from][to] *= RHO;
}
}
}
void emitDataFile(int bestIndex)
{
ofstream f1;
f1.open("Data_rank.txt");
antType antBest;
antBest = ants[bestIndex];
//f1<<antBest.curCity<<" "<<antBest.tourLength<<"\n";
int i;
for(i=0;i<MAX_CITIES;i++)
{
f1<<antBest.path[i]<<" ";
}
f1.close();
f1.open("city_data_rank.txt");
for(i=0;i<MAX_CITIES;i++)
{
f1<<cities[i].x<<" "<<cities[i].y<<"\n";
}
f1.close();
}
int main()
{
int curTime = 0;
cout<<"ACO-Rank:";
cout<<"MaxTime="<<MAX_TIME;
srand(time(NULL));
init();
while( curTime++ < MAX_TIME)
{
if( simulateAnts() == 0)
{
sortAnts();
updateTrails();
if(curTime != MAX_TIME)
restartAnts();
cout<<"\nTime is "<<curTime<<"("<<best<<")";
}
}
cout<<"\nRank: Best tour = "<<best<<endl<<endl<<endl;
emitDataFile(bestIndex);
return 0;
}
| true |
5ce1546da29653169f8df2e2b074f3301eca191d | C++ | katejim/study | /c++/ha2/errors.h | UTF-8 | 1,575 | 3.203125 | 3 | [] | no_license | #ifndef ERRORS_HPP
#define ERRORS_HPP
#include <stdexcept>
#include <string>
using std::string;
class Exception : public std::exception
{
string msg;
size_t erLine;
public:
Exception(size_t inLine, string const &message) : msg(message), erLine(inLine) {}
const char* what() const throw()
{
return msg.c_str();
}
size_t getLine() const
{
return erLine;
}
~Exception() throw () {}
};
class ParserException : public Exception
{
size_t erLine;
public:
explicit ParserException(size_t inLine, string const &message) : Exception(inLine, "you have synatax error " + message) {}
};
class EvaluatorException : public Exception
{
size_t erLine;
public:
explicit EvaluatorException(size_t inLine, string const &message) : Exception(inLine, message) {}
};
class DivByZero : public EvaluatorException
{
public:
explicit DivByZero(size_t inLine) : EvaluatorException(inLine, "you have divizion by zero") {}
};
class UndefVar : public EvaluatorException
{
public:
explicit UndefVar(size_t inLine, string const &inName) : EvaluatorException(inLine, "you have undefined variable " + inName) {}
};
class UndefFunc : public EvaluatorException
{
public:
explicit UndefFunc(size_t inLine, string const &inName) : EvaluatorException(inLine, "you have undefined function " + inName) {}
};
class ArgNumbMismatch : public EvaluatorException
{
public:
explicit ArgNumbMismatch(size_t inLine, string const &inName) : EvaluatorException(inLine, "arguments number mismatch for " + inName) {}
};
#endif
| true |
0984f6a6caca5f40b38e945d6615648af6ae7dc6 | C++ | Maazil/BomberRoyale | /bomberRoyale/jsonobjects/credits.h | UTF-8 | 484 | 2.859375 | 3 | [] | no_license | #ifndef BOMBER_ROYALE_CREDITS_H
#define BOMBER_ROYALE_CREDITS_H
#include <string>
class Credits {
public:
/**
* Read the credits from the file.
*
* @param filename is the path to the file
*/
bool readFromJson(const std::string& filename);
/**
* Return the credits text
* @return credits text in a string.
*/
std::string getText(){
return text;
}
protected:
std::string text;
};
#endif //BOMBER_ROYALE_CREDITS_H
| true |
9efd96b9b3bda3aa8b29b4102c70fec387816d7f | C++ | lapuglisi/ccpp | /studies/hash_table/hash_table.h | UTF-8 | 2,072 | 3.265625 | 3 | [] | no_license | #ifndef HASH_TABLE_H
#define HASH_TABLE_H
#include <iostream>
#include <memory.h>
#include <string.h>
namespace hash_table
{
///
/// Separate chaining Linked List
///
struct LinkedList
{
int data;
const char* key;
struct LinkedList* next;
LinkedList(const char *hash_key, int data) : data(data),
key(strdup(hash_key))
{
}
~LinkedList()
{
if (this->key != nullptr)
{
free((void*)this->key);
}
}
};
// Consider using template
struct HashTable
{
private:
static const size_t default_bucket_size_ = 19;
static const unsigned int hash_initial_value_ = 1977;
static const unsigned int hash_modifier_ = 39;
size_t size_;
LinkedList** bucket_;
unsigned int hash(const char *key);
public:
HashTable(int size = default_bucket_size_)
{
this->size_ = (size <= 0 ? default_bucket_size_ : size);
this->bucket_ = new LinkedList*[this->size_];
memset(this->bucket_, 0x00, this->size_);
}
~HashTable()
{
if (this->bucket_ != nullptr)
{
// WARNING! Change this
for (size_t slot = 0; slot < this->size_; slot++)
{
LinkedList* node = this->bucket_[slot];
while (node != nullptr)
{
LinkedList* next = node->next;
delete node;
node = node->next;
}
}
delete [] this->bucket_;
}
this->bucket_ = nullptr;
}
void put(const char* /* key */, int /* value */);
int get(const char* /* key */);
void remove(const char* /* key */);
void clear();
};
}
#endif // HASH_TABLE_H
| true |
b2d3f18189da81dfddea52cfd24606c1a1a20f00 | C++ | alohaeee/Corrosion | /src/driver/driver.hpp | UTF-8 | 2,126 | 2.90625 | 3 | [
"MIT"
] | permissive | #ifndef CORROSION_SRC_DRIVER_DRIVER_HPP_
#define CORROSION_SRC_DRIVER_DRIVER_HPP_
#include "utility/std_incl.hpp"
#include "lexer/lexer.hpp"
#include "parser/interface.hpp"
namespace corrosion
{
using CommandArgs = std::vector<std::string>;
class ArgReader
{
public:
static CommandArgs splitByWhiteSpaces(std::string_view view)
{
using namespace lexer;
std::size_t delta = 0;
CommandArgs args;
while (true)
{
auto iter = std::find_if(view.begin() + delta, view.end(), Alphabet::isWhitespace);
if (iter != view.end())
{
auto temp = std::distance(view.begin(), iter);
if(temp-delta != 0)
{
auto subArg = std::string(view.substr(delta, temp-delta));
args.push_back(subArg);
delta=temp+1;
}
else
{
delta++;
}
}
else
{
args.push_back(std::string(view.substr(delta,view.size()-delta)));
break;
}
}
return args;
}
};
class Driver
{
inline void emitErr(std::string_view errMsg)
{
CR_LOG_ERROR(errMsg);
m_reStatus = BAD;
}
public:
enum ReStatus : int
{
GOOD = 0,
BAD = 1
};
Driver(const CommandArgs& args)
{
greeting();
argEmit(args);
}
Driver(int argc, char** argv)
{
greeting();
}
Driver()
{
greeting();
}
inline void greeting()
{
CR_LOG_INFO("Corrosion | Rust ASM Compiler made with C++ only for learning purposes\n ");
}
void mainArg(int argc, char** argv)
{
CommandArgs args;
for(int i = 0; i < argc;i++)
{
args.push_back(argv[i]);
}
argEmit(args);
}
void argEmit(const CommandArgs& args)
{
if(args.size()==1)
{
auto&& [stmts,status] = m_parserInterface.getFastAst(args.back());
if(!status)
{
emitErr("we find errors on previous stages, can't continue to parse");
}
}
else
{
emitErr("for now compiler takes only one command line argument - file path to parse");
return;
}
}
ReStatus ret()
{
return m_reStatus;
}
private:
ReStatus m_reStatus = GOOD;
ParserInterface m_parserInterface;
};
}
#endif //CORROSION_SRC_DRIVER_DRIVER_HPP_
| true |
f74e41a35c287662fb5a57a5de14cc2287db448d | C++ | alisarogers/dictionaryTries | /cse100_pa2_startercode/DictionaryHashtable.cpp | UTF-8 | 734 | 3.203125 | 3 | [] | no_license | #include "util.h"
#include "DictionaryHashtable.h"
#include <unordered_set>
#include <string>
/* Create a new Dictionary that uses a Hashset back end */
DictionaryHashtable::DictionaryHashtable(){}
/* Insert a word into the dictionary. */
bool DictionaryHashtable::insert(std::string word)
{
std::pair<std::set<std::string>::iterator,bool> inserted;
return htbl.insert(word).second;
}
/* Return true if word is in the dictionary, and false otherwise */
bool DictionaryHashtable::find(std::string word) const
{
std::set<std::string>::iterator found;
// found = htbl.find(word);
if(htbl.find(word) == htbl.end())
{
return false;
} else { return true; }
}
/* Destructor */
DictionaryHashtable::~DictionaryHashtable(){}
| true |
9f3e889b23a4a91f0c2d9c4cd99db676e72a0dd7 | C++ | galin-kostadinov/Software-Engineering | /C++/Programming Basics with C++/12. Nested loops/simple_tasks/Building.cpp | UTF-8 | 782 | 3.15625 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main() {
int numOfFloors, numOfRooms;
cin >> numOfFloors >> numOfRooms;
char prefix = ' ';
int room = 0;
for (int i = numOfFloors - 1; i >= 0; i--) {
for (int j = 0; j < numOfRooms; j++) {
if (i % 2 == 0 && i < numOfFloors - 1 && numOfFloors > 1) {
prefix = 'A';
} else if (i % 2 != 0 && i < numOfFloors - 1 && numOfFloors > 1) {
prefix = 'O';
} else {
prefix = 'L';
}
room = (i + 1) * 10 + j;
if (j == numOfRooms - 1) {
cout << prefix << room << endl;
} else {
cout << prefix << room << " ";
}
}
}
return 0;
} | true |
d2eacea9ed44309a132bde0c38caa02947382d52 | C++ | agustinamartinez1044/ObjectOrientedProgramming | /Implementacion/Implementacion/src/clases/Comentario.cpp | UTF-8 | 522 | 2.796875 | 3 | [] | no_license | #include "../../include/clases/Comentario.h"
Comentario::Comentario(int id, DtFechaHora *fecha, string comentario){
this->id = id;
this->fechaEnvio = fecha;
this->comentario = comentario;
}
Comentario::~Comentario(){
delete fechaEnvio;
}
int Comentario::getId() {
return this->id;
}
string Comentario::getComentario() {
return this->comentario;
}
void Comentario::setComentario(string comentario) {
this->comentario = comentario;
}
void Comentario::setId( int id) {
this->id = id;
}
| true |
3e93dc952a95490bc49122e5ca8ede5439845c57 | C++ | sugawaray/filemanager | /tests/fm_map_impl.cpp | UTF-8 | 2,749 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <string>
#include <vector>
#include <fm.h>
#include <fm_map_impl.h>
#include "fixture/db.h"
#include "fm_map_impl.h"
using test::Db_fixture;
using namespace fm;
using std::string;
using std::vector;
namespace {
class Fixture : public Db_fixture {
public:
Fixture() {
categories.push_back("catA");
}
vector<string>& get_categories() {
return categories;
}
private:
vector<string> categories;
};
} // unnamed
START_TEST(should_return_file_type_given_file_value)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
map.set("dir1/file1", f.get_categories().begin(),
f.get_categories().end());
fail_unless(map.get_file_type("dir1/file1") == Type_file, "result");
}
END_TEST
START_TEST(should_return_dir_type_given_dir_value)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
auto& categories(f.get_categories());
map.set("dir1/dir2/file1", categories.begin(), categories.end());
fail_unless(map.get_file_type("dir1/dir2") == Type_dir, "result");
}
END_TEST
START_TEST(should_return_Not_exist_given_new_value)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
fail_unless(map.get_file_type("dir1/file1") == Not_exist, "result");
}
END_TEST
START_TEST(should_return_impossible_when_the_value_conflicts)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
auto& categories(f.get_categories());
map.set("dir1/file1", categories.begin(), categories.end());
fail_unless(map.get_file_type("dir1/file1/file2") == Impossible,
"result");
}
END_TEST
START_TEST(return_file_type_given_similar_name_files)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
auto& cat(f.get_categories());
map.set("dir1/file1", cat.begin(), cat.end());
map.set("dir1/file1.ext", cat.begin(), cat.end());
fail_unless(map.get_file_type("dir1/file1") == Type_file, "result");
}
END_TEST
START_TEST(return_dir_type_given_root_value)
{
Fixture f;
Fm_map_impl map(f.get_dbfilepath());
fail_unless(map.get_file_type("") == Type_dir, "result");
}
END_TEST
namespace fm {
namespace test {
namespace fm_map_impl {
TCase* create_get_file_type_tcase()
{
TCase* tcase(tcase_create("get_file_type"));
tcase_add_test(tcase, should_return_file_type_given_file_value);
tcase_add_test(tcase, should_return_dir_type_given_dir_value);
tcase_add_test(tcase, should_return_Not_exist_given_new_value);
tcase_add_test(tcase,
should_return_impossible_when_the_value_conflicts);
tcase_add_test(tcase, return_file_type_given_similar_name_files);
tcase_add_test(tcase, return_dir_type_given_root_value);
return tcase;
}
} // fm_map_impl
Suite* create_fm_map_impl_test_suite()
{
using namespace fm_map_impl;
Suite* suite(suite_create("fm_map_impl"));
suite_add_tcase(suite, create_get_file_type_tcase());
return suite;
}
} // test
} // fm
| true |
65d7ea12f7bae59f8f59efc1cd01babb92e5a0da | C++ | Chaitya62/ComputerGraphics | /code/mid_point_ellipse.cpp | UTF-8 | 1,612 | 2.90625 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<graphics.h>
#define HEIGHT 480
#define WIDTH 640
#define X(x) x+(WIDTH/2)
#define Y(y) (HEIGHT/2) - y
using namespace std;
void putpixelo(int x, int y, int color){
setlinestyle(SOLID_LINE, 1, 3);
line(X(-100), Y(100), X(100), Y(100));
putpixel(X(x), Y(y),color);
return;
}
int drawEllipse(int rx, int ry){
int x = 0, y = ry;
double p1 = ry*ry - rx*rx*ry + rx*rx/4;
putpixelo(x, y, RED);
while(2*rx*rx*y >= 2*ry*ry*x){
if(p1 < 0){
x+=1;
y = y;
p1 = p1 + 2*ry*ry*x + ry*ry;
}else{
x+=1;
y-=1;
p1 = p1+2*ry*ry*x + ry*ry - 2*rx*rx*y;
}
putpixelo(x, y, RED);
putpixelo(-x,y,YELLOW);
putpixelo(-x,-y, GREEN);
putpixelo(x, -y, BLUE);
}
double p2 = ry*ry*(x+0.5)*(x+0.5) + rx*rx*(y-1)*(y-1) - rx*rx*ry*ry;
while(x != rx && y != 0){
if(p2 > 0){
y-=1;
x = x;
p2 = p2 - 2*rx*rx*y + rx*rx;
}else{
y-=1;
x+=1;
p2 = p2 - 2*rx*rx*y + 2*ry*ry*(x) + rx*rx;
}
putpixelo(x, y, WHITE);
putpixelo(-x,y,YELLOW);
putpixelo(-x,-y, GREEN);
putpixelo(x, -y, BLUE);
}
x = rx;
y = 0;
putpixel(x, y, RED);
putpixel(-x,y,YELLOW);
putpixel(-x,-y, GREEN);
putpixel(x, -y, BLUE);
return 0;
}
int main(){
int gd = DETECT,gm;
initgraph(&gd, &gm, NULL);
line(X(-(WIDTH/2)), Y(0), X(WIDTH/2), Y(0));
line(X(0), Y(HEIGHT/2), X(0), Y(-HEIGHT/2));
drawEllipse(200, 100);
drawEllipse(201, 101);
drawEllipse(199, 99);
drawEllipse(202, 102);
drawEllipse(203, 103);
drawEllipse(204, 104);
drawEllipse(205, 105);
getchar();
closegraph();
return 0;
}
| true |
deb0fe25bed2b680ed65905744d2f7990881c6c1 | C++ | shoeisha-books/dokushu-cpp | /ch01/list_1.6/main.cpp | UTF-8 | 197 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <iostream>
int main()
{
int a = 1 + 2 * 3 - 4;
std::cout << a << std::endl;
int b = (1 + 2) * (3 - 4); // 括弧の中から計算
std::cout << b << std::endl;
}
| true |
c5e2e1d35f5ccaaf8f7cb6a1f09bdd1c6caafb65 | C++ | zeropoint-t/GCSDD | /Data Structures & Algorithm I/Project2/House.h | UTF-8 | 894 | 3.125 | 3 | [] | no_license |
#ifndef House_h
#define House_h
#include <iostream>
#include "Score.h"
class House{
public:
House();
House(Score* score, double price, double milesFromMainCity, double squareFootage, double numOfRooms, double numOfBathrooms);
~House();
bool operator>(const House& house);
bool operator>=(const House& house);
bool operator<(const House& house);
bool operator<=(const House& house);
double getPrice() const;
double getMilesFromMainCity() const;
double getSquareFootage() const;
double getNumOfRooms() const;
double getNumOfBathrooms() const;
double getScore() const;
private:
Score* score;
double price = 0;
double milesFromMainCity = 0;
double squareFootage = 0;
double numOfRooms = 0;
double numOfBathrooms = 0;
};
#endif | true |
c872953a3e64cb5501666d529bbc540270951a50 | C++ | sonnh-uit/TheSis | /SOURCE/file_rw.cpp | UTF-8 | 595 | 3.109375 | 3 | [] | no_license | #include "file_rw.h"
void write_ob(string file, string content)
{
ofstream myfile;
myfile.open(file, ios_base::app);
if (myfile.is_open())
{
myfile << content;
myfile.close();
}
else
cout << "Can't write, Unable to open file " << file << endl;
}
string read_ob(string file)
{
string line;
ifstream myfile(file);
string result = "";
if (myfile.is_open())
{
while (getline(myfile, line))
{
result += line;
}
myfile.close();
}
else
return "NULL";
return result;
}
| true |
6dc12fa93aaaeb138e37e39d05803177924a1f0c | C++ | lynren/uva-online-judge | /10035 Primary Arithmetic/solution.cxx | UTF-8 | 1,534 | 3.84375 | 4 | [] | no_license | /* Lyndon Renaud
* 2020-10-04
*
* Solution:
* Initially, we have 0 total carries and carry value set to 0
* Starting from the right most numbers i1, j1, we check
* if i1 + j1 + carry > 9. If this is true, we carry, so we set carry to 1
* and increment our carry counter. Else we set carry to 0.
* We keep moving through the numbers from right to left, checking
* if i + j + carry > 9 and incrementing the carry counter accordingly
*/
#include <iostream>
using namespace std;
int main(){
int n1, n2;
while(cin >> n1 >> n2){
if(n1 == 0 && n2 == 0){
break;
}
int carry = 0;
int total_carries = 0;
while(n1 > 0 || n2 > 0){
int k1 = n1 % 10;
int k2 = n2 % 10;
n1 /= 10;
n2 /= 10;
if(k1 + k2 + carry > 9){
carry = 1;
}
else
carry = 0;
total_carries += carry;
}
if (total_carries > 1){
cout << total_carries << " carry operations.\n";
}
else if (total_carries == 1){
cout << "1 carry operation.\n";
}
else{
cout << "No carry operation.\n";
}
}
return 0;
}
| true |
7534590335472d443aa12204dc3c60e07c6d8bb7 | C++ | KaYBlitZ/CS3113-HW | /CS3113_HW_6/CS3113 HW6/Asteroid.cpp | UTF-8 | 4,453 | 3.0625 | 3 | [] | no_license | #include "Asteroid.h"
Asteroid::Asteroid() : Entity(0.0f, 0.0f, 0.0f), velocity(0.0f), shape(nullptr) {}
Asteroid::Asteroid(float x, float y, float rotation, float velocity, AsteroidSize size) : Entity(x, y, rotation), velocity(velocity), size(size) {
switch (size) {
case LARGE:
radius = 0.2f;
numPoints = 8;
shape = new GLfloat[numPoints * 2] {
0.0f, radius,
-radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
-radius, 0.0f,
-radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
0.0f, -radius,
radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
radius, 0.0f,
radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
};
break;
case MEDIUM:
radius = 0.1f;
numPoints = 7;
shape = new GLfloat[numPoints * 2] {
-radius, -radius / 3,
-radius / 2, -radius / 2,
0.0f, -radius,
4 * radius / 5, -radius / 2,
radius, 0.0f,
radius / 2, radius,
-radius / 2, radius
};
break;
case SMALL:
radius = 0.05f;
numPoints = 5;
shape = new GLfloat[numPoints * 2] {
-4 * radius / 5, radius / 2,
3 * radius / 5, 4 * radius / 5,
radius, 0.0f,
radius / 2, 4 * radius / 5,
-4 * radius / 5, -radius / 2,
};
break;
}
}
Asteroid::~Asteroid() {
delete [] shape;
}
Asteroid::Asteroid(const Asteroid& rhs) : Entity(rhs), velocity(rhs.velocity), size(rhs.size), numPoints(rhs.numPoints) {
switch (size) {
case LARGE:
shape = new GLfloat[numPoints * 2] {
0.0f, radius,
-radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
-radius, 0.0f,
-radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
0.0f, -radius,
radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
radius, 0.0f,
radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
};
break;
case MEDIUM:
shape = new GLfloat[numPoints * 2] {
-radius, -radius / 3,
-radius / 2, -radius / 2,
0.0f, -radius,
4 * radius / 5, -radius / 2,
radius, 0.0f,
radius / 2, radius,
-radius / 2, radius
};
break;
case SMALL:
shape = new GLfloat[numPoints * 2] {
-4 * radius / 5, radius / 2,
3 * radius / 5, 4 * radius / 5,
radius, 0.0f,
radius / 2, 4 * radius / 5,
-4 * radius / 5, -radius / 2,
};
break;
}
}
Asteroid& Asteroid::operator=(const Asteroid& rhs) {
if (this != &rhs) {
Entity::operator=(rhs);
velocity = rhs.velocity;
size = rhs.size;
numPoints = rhs.numPoints;
switch (size) {
case LARGE:
shape = new GLfloat[numPoints * 2] {
0.0f, radius,
-radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
-radius, 0.0f,
-radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
0.0f, -radius,
radius * cos(45 * Entity::degToRadRatio), -radius * sin(45 * Entity::degToRadRatio),
radius, 0.0f,
radius * cos(45 * Entity::degToRadRatio), radius * sin(45 * Entity::degToRadRatio),
};
break;
case MEDIUM:
shape = new GLfloat[numPoints * 2] {
-radius, -radius / 3,
-radius / 2, -radius / 2,
0.0f, -radius,
4 * radius / 5, -radius / 2,
radius, 0.0f,
radius / 2, radius,
-radius / 2, radius
};
break;
case SMALL:
shape = new GLfloat[numPoints * 2] {
-4 * radius / 5, radius / 2,
3 * radius / 5, 4 * radius / 5,
radius, 0.0f,
radius / 2, 4 * radius / 5,
-4 * radius / 5, -radius / 2,
};
break;
}
}
return *this;
}
void Asteroid::fixedUpdate() {
x += velocity * cos(rotation * Entity::degToRadRatio) * FIXED_TIMESTEP;
y += velocity * sin(rotation * Entity::degToRadRatio) * FIXED_TIMESTEP;
if (x > 1.33f) {
x = -1.33f;
}
else if (x < -1.33f) {
x = 1.33f;
}
if (y > 1.0f) {
y = -1.0f;
}
else if (y < -1.0f) {
y = 1.0f;
}
}
void Asteroid::render() {
createMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glMultMatrixf(matrix.ml);
glVertexPointer(2, GL_FLOAT, 0, shape);
glEnableClientState(GL_VERTEX_ARRAY);
glLineWidth(3.0f);
glDrawArrays(GL_POLYGON, 0, numPoints);
glPopMatrix();
} | true |
e677995032798aed695a6415dc6aff3c70838fd4 | C++ | zxy3/cpp_primer_practice | /test10.33.cpp | GB18030 | 655 | 2.53125 | 3 | [] | no_license | /**=================================================================================================
* @file test10.33.cpp.
*
* Implements the test 10.33 class
* ϰ 10.33 д һļļļ Ӧ
* ʹ istream_iterator ȡ ʹ ostream_iteratorдһļ ÿֵ֮һո
* żдڶļ ÿֵռһС
*===============================================================================================**/
| true |
a8899a6877a7f06affe952361b2f05b4dbbb41a9 | C++ | pydata/numexpr | /numexpr/str-two-way.hpp | UTF-8 | 14,424 | 2.609375 | 3 | [
"MIT"
] | permissive | /* Byte-wise substring search, using the Two-Way algorithm.
* Copyright (C) 2008, 2010 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*/
/* Before including this file, you need to include <string.h>, and define:
RETURN_TYPE A macro that expands to the return type.
AVAILABLE(h, h_l, j, n_l) A macro that returns nonzero if there are
at least N_L bytes left starting at
H[J]. H is 'unsigned char *', H_L, J,
and N_L are 'size_t'; H_L is an
lvalue. For NUL-terminated searches,
H_L can be modified each iteration to
avoid having to compute the end of H
up front.
For case-insensitivity, you may optionally define:
CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
characters of P1 and P2 are equal.
CANON_ELEMENT(c) A macro that canonicalizes an element
right after it has been fetched from
one of the two strings. The argument
is an 'unsigned char'; the result must
be an 'unsigned char' as well.
This file undefines the macros documented above, and defines
LONG_NEEDLE_THRESHOLD.
*/
#include <limits.h>
/*
Python 2.7 (the only Python 2.x version supported as of now and until 2020)
is built on windows with Visual Studio 2008 C compiler. That dictates that
the compiler which must be used by authors of third party Python modules.
See https://mail.python.org/pipermail/distutils-sig/2014-September/024885.html
Unfortunately this version of Visual Studio doesn't claim to be C99 compatible
and in particular it lacks the stdint.h header. So we have to replace it with
a public domain version.
Visual Studio 2010 and later have stdint.h.
*/
#ifdef _MSC_VER
#if _MSC_VER <= 1500
#include "win32/stdint.h"
#endif
#else
#include <stdint.h>
#endif
/* We use the Two-Way string matching algorithm, which guarantees
linear complexity with constant space. Additionally, for long
needles, we also use a bad character shift table similar to the
Boyer-Moore algorithm to achieve improved (potentially sub-linear)
performance.
See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm
*/
/* Point at which computing a bad-byte shift table is likely to be
worthwhile. Small needles should not compute a table, since it
adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
speedup no greater than a factor of NEEDLE_LEN. The larger the
needle, the better the potential performance gain. On the other
hand, on non-POSIX systems with CHAR_BIT larger than eight, the
memory required for the table is prohibitive. */
#if CHAR_BIT < 10
# define LONG_NEEDLE_THRESHOLD 32U
#else
# define LONG_NEEDLE_THRESHOLD SIZE_MAX
#endif
#define MAX(a, b) ((a < b) ? (b) : (a))
#ifndef CANON_ELEMENT
# define CANON_ELEMENT(c) c
#endif
#ifndef CMP_FUNC
# define CMP_FUNC memcmp
#endif
/* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
Return the index of the first byte in the right half, and set
*PERIOD to the global period of the right half.
The global period of a string is the smallest index (possibly its
length) at which all remaining bytes in the string are repetitions
of the prefix (the last repetition may be a subset of the prefix).
When NEEDLE is factored into two halves, a local period is the
length of the smallest word that shares a suffix with the left half
and shares a prefix with the right half. All factorizations of a
non-empty NEEDLE have a local period of at least 1 and no greater
than NEEDLE_LEN.
A critical factorization has the property that the local period
equals the global period. All strings have at least one critical
factorization with the left half smaller than the global period.
Given an ordered alphabet, a critical factorization can be computed
in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
larger of two ordered maximal suffixes. The ordered maximal
suffixes are determined by lexicographic comparison of
periodicity. */
static size_t
critical_factorization (const unsigned char *needle, size_t needle_len,
size_t *period)
{
/* Index of last byte of left half, or SIZE_MAX. */
size_t max_suffix, max_suffix_rev;
size_t j; /* Index into NEEDLE for current candidate suffix. */
size_t k; /* Offset into current period. */
size_t p; /* Intermediate period. */
unsigned char a, b; /* Current comparison bytes. */
/* Invariants:
0 <= j < NEEDLE_LEN - 1
-1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
min(max_suffix, max_suffix_rev) < global period of NEEDLE
1 <= p <= global period of NEEDLE
p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
1 <= k <= p
*/
/* Perform lexicographic search. */
max_suffix = SIZE_MAX;
j = 0;
k = p = 1;
while (j + k < needle_len)
{
a = CANON_ELEMENT (needle[j + k]);
b = CANON_ELEMENT (needle[(size_t)(max_suffix + k)]);
if (a < b)
{
/* Suffix is smaller, period is entire prefix so far. */
j += k;
k = 1;
p = j - max_suffix;
}
else if (a == b)
{
/* Advance through repetition of the current period. */
if (k != p)
++k;
else
{
j += p;
k = 1;
}
}
else /* b < a */
{
/* Suffix is larger, start over from current location. */
max_suffix = j++;
k = p = 1;
}
}
*period = p;
/* Perform reverse lexicographic search. */
max_suffix_rev = SIZE_MAX;
j = 0;
k = p = 1;
while (j + k < needle_len)
{
a = CANON_ELEMENT (needle[j + k]);
b = CANON_ELEMENT (needle[max_suffix_rev + k]);
if (b < a)
{
/* Suffix is smaller, period is entire prefix so far. */
j += k;
k = 1;
p = j - max_suffix_rev;
}
else if (a == b)
{
/* Advance through repetition of the current period. */
if (k != p)
++k;
else
{
j += p;
k = 1;
}
}
else /* a < b */
{
/* Suffix is larger, start over from current location. */
max_suffix_rev = j++;
k = p = 1;
}
}
/* Choose the longer suffix. Return the first byte of the right
half, rather than the last byte of the left half. */
if (max_suffix_rev + 1 < max_suffix + 1)
return max_suffix + 1;
*period = p;
return max_suffix_rev + 1;
}
/* Return the first location of non-empty NEEDLE within HAYSTACK, or
NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
Performance is guaranteed to be linear, with an initialization cost
of 2 * NEEDLE_LEN comparisons.
If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
static RETURN_TYPE
two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
size_t i; /* Index into current byte of NEEDLE. */
size_t j; /* Index into current window of HAYSTACK. */
size_t period; /* The period of the right half of needle. */
size_t suffix; /* The index of the right half of needle. */
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
suffix = critical_factorization (needle, needle_len, &period);
/* Perform the search. Each iteration compares the right half
first. */
if (CMP_FUNC (needle, needle + period, suffix) == 0)
{
/* Entire needle is periodic; a mismatch can only advance by the
period, so use memory to avoid rescanning known occurrences
of the period. */
size_t memory = 0;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
i = MAX (suffix, memory);
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (memory < i + 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i + 1 < memory + 1)
return (RETURN_TYPE) (haystack + j);
/* No match, so remember how many repetitions of period
on the right half were scanned. */
j += period;
memory = needle_len - period;
}
else
{
j += i - suffix + 1;
memory = 0;
}
}
}
else
{
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
period = MAX (suffix, needle_len - suffix) + 1;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
i = suffix;
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i == SIZE_MAX)
return (RETURN_TYPE) (haystack + j);
j += period;
}
else
j += i - suffix + 1;
}
}
return NULL;
}
/* Return the first location of non-empty NEEDLE within HAYSTACK, or
NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
Performance is guaranteed to be linear, with an initialization cost
of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
sublinear performance is not possible. */
static RETURN_TYPE
two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
size_t i; /* Index into current byte of NEEDLE. */
size_t j; /* Index into current window of HAYSTACK. */
size_t period; /* The period of the right half of needle. */
size_t suffix; /* The index of the right half of needle. */
size_t shift_table[1U << CHAR_BIT]; /* See below. */
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
suffix = critical_factorization (needle, needle_len, &period);
/* Populate shift_table. For each possible byte value c,
shift_table[c] is the distance from the last occurrence of c to
the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
for (i = 0; i < 1U << CHAR_BIT; i++)
shift_table[i] = needle_len;
for (i = 0; i < needle_len; i++)
shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
/* Perform the search. Each iteration compares the right half
first. */
if (CMP_FUNC (needle, needle + period, suffix) == 0)
{
/* Entire needle is periodic; a mismatch can only advance by the
period, so use memory to avoid rescanning known occurrences
of the period. */
size_t memory = 0;
size_t shift;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
if (memory && shift < period)
{
/* Since needle is periodic, but the last period has
a byte out of place, there can be no match until
after the mismatch. */
shift = needle_len - period;
}
memory = 0;
j += shift;
continue;
}
/* Scan for matches in right half. The last byte has
already been matched, by virtue of the shift table. */
i = MAX (suffix, memory);
while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len - 1 <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (memory < i + 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i + 1 < memory + 1)
return (RETURN_TYPE) (haystack + j);
/* No match, so remember how many repetitions of period
on the right half were scanned. */
j += period;
memory = needle_len - period;
}
else
{
j += i - suffix + 1;
memory = 0;
}
}
}
else
{
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
size_t shift;
period = MAX (suffix, needle_len - suffix) + 1;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
j += shift;
continue;
}
/* Scan for matches in right half. The last byte has
already been matched, by virtue of the shift table. */
i = suffix;
while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len - 1 <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i == SIZE_MAX)
return (RETURN_TYPE) (haystack + j);
j += period;
}
else
j += i - suffix + 1;
}
}
return NULL;
}
#undef AVAILABLE
#undef CANON_ELEMENT
#undef CMP_FUNC
#undef MAX
#undef RETURN_TYPE
| true |
5c609577cf791f79b5098fb6e56794b7eee741cb | C++ | Vidrohi/EffectiveCPP | /EffCPP/Chapter6/PerformanceTester.cpp | UTF-8 | 4,051 | 3.265625 | 3 | [] | no_license | #include "NonPOD.h"
#include "PerformanceTester.h"
#include <vector>
void PrintNonPODByVal(Performance::NonPOD values)
{
printf("[PRINT_PASS_BY_VALUE] , NonPOD %s with id %i and value %f was printed \n", values.GetName().c_str(), values.GetId(), values.GetValue());
}
void PrintNonPODConstRef(const Performance::NonPOD& values)
{
printf("[PRINT_PASS_BY_REF] , NonPOD %s with id %i and value %f was printed \n", values.GetName().c_str(), values.GetId(), values.GetValue());
}
void Performance::Tester::RunTest()
{
// Only default constructor
NonPOD defaultConstructed;
printf("**********************************************\n");
// Calls NonPOD(const std::string& name)
NonPOD constructedWithName(std::string("CONSTRUCTED_WITH_NAME"));
printf("**********************************************\n");
// Calls NonPOD(const std::string& name)
NonPOD constructedWithCstrPromotion("CONSTRUCTED_WITH_C_STR_PROMOTION");
printf("**********************************************\n");
// Promotes a float to a config and constructs
NonPOD constructedWithFloatPromotedToConfig(7.0f);
printf("**********************************************\n");
// Copy constructs a NonPOD object and then calls the Print method
PrintNonPODByVal(constructedWithName);
printf("**********************************************\n");
// Directly calls the print method on a reference to the passed object
PrintNonPODConstRef(constructedWithName);
printf("**********************************************\n");
// Calls only the set value method
constructedWithName.SetValue(10.0f);
printf("**********************************************\n");
// Calls the assignment operator only
constructedWithFloatPromotedToConfig = constructedWithName;
printf("**********************************************\n");
// Constructs a NonPODConfig object, Promotes it to a NonPOD object and then calls the assignment operator
constructedWithFloatPromotedToConfig = NonPODConfig(15.0f);
printf("**********************************************\n");
printf("***************[VECTOR TESTS]*****************\n");
std::vector<NonPOD> nonPodVect;
// Calls the copy constructor (and then whatever the vector does)
nonPodVect.push_back(constructedWithName);
printf("**********************************************\n");
// Constructs the nonpod config
// Then constructs the non pod
// Copy constructs from this nonpod into the vector
// Copy constructs the element already in there (resizing of the vector I imagine)
nonPodVect.push_back(NonPODConfig(32.0));
printf("**********************************************\n");
// Constructs the new NonPOD
// Copy constructs the new NonPOD
// Copy constructs both of the other elements as well ! (vector resizing ?)
nonPodVect.push_back(NonPOD("Messing_With_vector"));
printf("**********************************************\n");
printf("*************[RESERVED 6 ELT]*****************\n");
// Reserves space for 6 elements
nonPodVect.reserve(6);
// Copy constructs pre existing elements
// Constructs a new NonPOD
// Copy constructs the new NonPOD
nonPodVect.push_back(NonPOD("VectorElt4"));
printf("**********************************************\n");
// Constructs a new NonPOD
// Copy constructs Only that element
nonPodVect.push_back(NonPOD("VectorElt5"));
printf("**********************************************\n");
// Constructs a new NonPOD
// Copy constructs Only that element
nonPodVect.push_back(NonPOD("VectorElt6"));
printf("**********************************************\n");
// Constructs a new NonPOD
// Copy constructs that element
// Copy constructs every pre existing element
nonPodVect.push_back(NonPOD("VectorElt7"));
printf("**********************************************\n");
} | true |
ac7322a9ef9b9889c9baa30b4db5da3370991e3d | C++ | yugpatell/text-based-rpg | /Character/Knight.cpp | UTF-8 | 1,052 | 3.171875 | 3 | [] | no_license | #include "Knight.h"
#include "../AttackStrategy/KnightAttack.h"
#include <iostream>
using namespace std;
Knight::Knight(string name, characterType role) {
attackMethod = new KnightAttack();
chestplate = nullptr;
leggings = nullptr;
weapon = nullptr;
this->name = name;
this->role = role;
maxHP = 10;
currHP = 10;
atk = 5;
defense = 5;
level = 1;
currXP = 0;
maxXP = 100;
}
int Knight::attack(Mob * currMob) {
try {
if (this->attackMethod == nullptr) {
throw std::invalid_argument("Nullptr detected");
}
else {
return this->attackMethod->attackMob(this, currMob);
}
}
catch (std::invalid_argument error) {
cerr << error.what() << endl;
return -1;
}
}
void Knight::levelUp() {
while (currXP >= maxXP) {
cout << "You have lvled up!" << endl;
maxHP += 3;
currHP += 3;
atk += 2;
defense += 5;
level += 1;
currXP = currXP - maxXP;
maxXP += 25;
}
}
| true |
59baf065c3c5f4cc10d1c5bb0be3fae8208cc03e | C++ | klub-programatoru/RobotKarel | /Karel/main.cpp | UTF-8 | 2,906 | 2.625 | 3 | [] | no_license | #include "graphics.h"
#include <SDL2/SDL.h>
#include <stdio.h>
#include <cstdio>
#include <math.h>
#include "karel.h"
#include "wall.h"
#include "background.h"
#include "karel.h"
#include "obdelnik.h"
#include "finish.h"
#include "game.h"
#include <list>
#include <vector>
#include <string>
#include <iostream>
int z = 159;
int delay_s = 1500;
int delay_m = 750;
int delay_p = 250;
Game game(z);
Karel karel(game.x, game.y, game.width, game.height);
#define zed game.wall
#define hranice game.end
#define zadan 0
#define jednoducha 15
#define strdni 50
#define tezka 75
#define BILA 255, 255, 255
#define CERNA 0, 0, 0
#define CERVENA 255, 0, 0
#define ZELENA 0, 255, 0
#define MODRA 0, 0, 255
void start(int obtiznost)
{
game.init(obtiznost);
game.kresli();
SDL_Delay(delay_s);
}
void end()
{
while (!game.quit)
{
game.kresli();
// hlídání kláves
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
// ESCAPE = KONEC
case SDLK_ESCAPE:
game.obrazovka->zavri();
game.quit = true;
return;
// ŠIPKA DOLŮ = POHYB
// case SDLK_DOWN:
// (*game.k)->move();
// break;
// // ŠIPKA DOLEVA = OTOČKA
// case SDLK_LEFT:
// (*game.k)->turn();
// break;
// // MEZERNIK
// case SDLK_SPACE:
// game.obdelniky.push_back(new Obdelnik(10, 10, 10, (*game.k)->x, (*game.k)->y, game.width / 12, game.height / 12));
}
break;
}
}
}
game.obrazovka->zavri();
}
void krok()
{
game.kresli();
SDL_Delay(delay_m);
game.move();
game.kresli();
// hlídání kláves
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_SPACE:
delay_s = 0;
delay_m = 0;
delay_p = 0;
return;
}
break;
}
}
}
void otoc()
{
game.kresli();
SDL_Delay(delay_m);
game.turn();
game.kresli();
}
void poloz(int r, int g, int b)
{
game.kresli();
SDL_Delay(delay_p);
game.place(r, g, b);
game.kresli();
}
#define krok krok()
#define otoc otoc()
//MAIN LOOP
int main(int arg, char *argv[])
{
start(0);
/* Tady je prostor pro vaš příkazy:*/
//krok;
//otoc;
//poloz(BILA);
/* Konce prostoru pro příkazy!*/
end();
return 1;
} | true |
301a9dc395f97f662d03371753884d6dbf685050 | C++ | stephengroat/OSVR-Core | /examples/plugin-hosts/BasicPluginLoader.cpp | UTF-8 | 1,615 | 2.703125 | 3 | [
"Apache-2.0",
"NCSA",
"BSL-1.0",
"BSD-3-Clause",
"MPL-2.0",
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | /** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/PluginHost/RegistrationContext.h>
// Library/third-party includes
// - none
// Standard includes
#include <iostream>
#include <exception>
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cerr << "Must supply a plugin name to load." << std::endl;
return 1;
}
osvr::pluginhost::RegistrationContext ctx;
try {
std::cout << "Trying to load plugin " << argv[1] << std::endl;
ctx.loadPlugin(argv[1]);
std::cout << "Successfully loaded plugin, control returned to host "
"application!" << std::endl;
return 0;
} catch (std::exception &e) {
std::cerr << "Caught exception tring to load " << argv[1] << ": "
<< e.what() << std::endl;
return 1;
}
std::cerr << "Failed in a weird way - not a std::exception." << std::endl;
return 2;
}
| true |
e41ba4d2314265cc0f81b08e59baf833a7959e06 | C++ | AGmanufacture/lightmashine | /lightmashine/RecieverChannel.cpp | UTF-8 | 1,277 | 3.03125 | 3 | [] | no_license | #include "RecieverChannel.h"
RecieverChannel::RecieverChannel(int pin, int minSignal, int maxSignal) {
_maxSignal = maxSignal;
_minSignal = minSignal;
_pin = pin;
_value = 0;
_lastState = LOW;
pinMode(pin, INPUT);
_stateChanged = micros();
_dropNextValue = false;
}
void RecieverChannel::read() {
int newState = digitalRead(_pin);
if (newState != _lastState) {
if (_lastState == LOW) {
// change from low to high, start measuring time
_stateChanged = micros();
} else {
// _lastState == HIGH
// change from high to low, calculate passed time
long time = micros() - _stateChanged;
if (time > MIN_VALUE) {
_value = trimValueToBoundaries(time);
}
if (_dropNextValue) {
_value = 0;
_dropNextValue = false;
}
}
_lastState = newState;
}
}
int RecieverChannel::getValue() {
return _value;
}
int RecieverChannel::trimValueToBoundaries(long val) {
if (val < _minSignal) {
return _minSignal;
}
if (val > _maxSignal) {
return _maxSignal;
}
return val;
}
int RecieverChannel::getMaxSignal() {
return _maxSignal;
}
int RecieverChannel::getMinSignal() {
return _minSignal;
}
void RecieverChannel::dropNextValue() {
_dropNextValue = true;
}
| true |
35dd866711dd00c8ff425fbe7919dd5d1763ae4e | C++ | jasonrohrer/OneLife | /server/networkStressTest.cpp | UTF-8 | 1,611 | 2.515625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #include <stdio.h>
#include "minorGems/network/Socket.h"
#include "minorGems/network/SocketServer.h"
#include "minorGems/system/Thread.h"
#define buffSize 8192
int main() {
printf( "Listening on port 9000\n" );
SocketServer server( 9000, 10 );
Socket *sock = server.acceptConnection( -1 );
if( sock != NULL ) {
printf( "Got connection\n" );
char fail = false;
int totalSent = 0;
int sleepCount = 0;
unsigned char buffer[buffSize];
int totalSleep = 500;
while( ! fail ) {
int splitCount = 64;
int len = buffSize / splitCount;
int splitSleep = totalSleep / splitCount;
for( int i=0; i<splitCount; i++ ) {
int numSent =
sock->send( &( buffer[ i * len ] ),
len,
false, false );
if( numSent != len ) {
fail = true;
}
else {
totalSent += numSent;
}
Thread::staticSleep( splitSleep );
}
// sleep after every full buffer
//Thread::staticSleep( 1000 );
if( totalSent % 131072 == 0 ) {
printf( "Sent %d\n", totalSent );
}
}
printf( "Total sent before fail: %d\n", totalSent );
delete sock;
}
}
| true |
cc7c61f2853ff0fb3b0bebd6746f15b9d03c06e6 | C++ | IrinaStarshova/VendingMachine | /vendingMachine/VendingMachine/machine.cpp | UTF-8 | 4,549 | 3.28125 | 3 | [] | no_license | #include "machine.h"
#include "constants.h"
#include "dateTime.h"
#include "fileStatistics.h"
#include "createAndFreeFilePointer.h"
#include <iostream>
#include <random>
#include <chrono>
#include <algorithm>
using namespace std;
Machine::Machine() : totalProducts(0)
{
cellsNames.reserve(cellsCount);
productsNames.reserve(cellsCount);
prices.reserve(cellsCount);
cells.reserve(cellsCount);
initCellsNames();
initProductsNames();
initPrices();
fillMachine();
}
void Machine::initProductsNames()
{
productsNames = { "Chocolate" , "Juice", "Cookies", "Water", "IceTea", "Croissant", "Soda", "Chips", "Candies" };
default_random_engine rand(static_cast<unsigned>(chrono::system_clock::now().time_since_epoch().count()));
shuffle(begin(productsNames), end(productsNames), rand);
}
void Machine::initPrices()
{
for (int i = 0; i < cellsCount; ++i)
{
prices.push_back(1 + rand() % 100);
}
}
void Machine::initCellsNames()
{
for (int i = 0; i < lettersCount; ++i)
{
for (int j = 1; j <= maxNumber; ++j)
{
string name;
name.push_back(firstLetter + i);
name.push_back(j + '0');
cellsNames.push_back(name);
}
}
}
void Machine::fillMachine()
{
for (int i = 0; i < cellsCount; ++i)
{
Cell C(cellsNames[i], productsNames[i], prices[i]);
cells.push_back(C);
totalProducts += cells.back().getnumberOfProducts();
}
}
void Machine::displayMenu() const
{
cout << "\n1 - DEVICE MENU" << endl;
cout << "2 - BUY A PRODUCT" << endl;
cout << "3 - SAVE PURCHASES HISTORY" << endl;
cout << "4 - SAVE PURCHASES STATISTICS" << endl;
cout << "5 - SAVE AVAILABLE PRODUCTS STATISTICS" << endl;
cout << "6 - EXIT\n" << endl;
}
void Machine::displayMachineMenu() const
{
for (const auto& i:cells)
{
i.display();
}
}
void Machine::Run()
{
int enteredNumber;
do
{
displayMenu();
cout << "Enter menu item number: ";
cin >> enteredNumber;
if (cin.fail())
{
cout << "\nInvalid value of menu item number entered\nEnter the menu item number from the list below\n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
switch (enteredNumber)
{
case 1: displayMachineMenu(); break;
case 2: buyProduct(); break;
case 3:
case 4:
case 5:
{
FileStatistics* file = createStatisticsFile(enteredNumber);
if (file)
file->writeFileStatistics(this);
freeStatisticsFile(file);
break;
}
case 6: break;
default:cout << "\nInvalid value of menu item number entered\nEnter the menu item number from the list below\n" << endl; break;
}
} while (enteredNumber != 6);
}
void Machine::buyProduct()
{
string cellNameEntered;
cout << "Enter cell name:";
cin >> cellNameEntered;
int cellNameLetter = toupper(cellNameEntered.front()); //на случай, если пользователь введет строчную букву вместо заглавной
int cellNameNumber = cellNameEntered.back() - '0';
if ((cellNameEntered.length() == 2) && (cellNameLetter >= firstLetter && (cellNameLetter < firstLetter + lettersCount)
&& (cellNameNumber > 0 && cellNameNumber <= maxNumber)))
{
int index = (maxNumber * (cellNameLetter - firstLetter) + cellNameNumber - 1); //подсчет индекса ячейки, из которой производится покупка
if (cells[index].isCellProductsEmpty())
cout << "\nCell " << cells[index].getName() << " is empty\n" << endl;
else
{
int amountOfMoney;
cout << "Enter amount of money:";
cin >> amountOfMoney;
if (amountOfMoney < cells[index].getPriceOfProduct())
cout << "\nNot enough money for purchase\n" << endl;
else
{
DateAndTime D;
Purchase purchase(D, cells[index].getNameOfProduct(), cells[index].getPriceOfProduct());
purchasesHistory.push_back(purchase);
cout << "\nPurchased product " << cells[index].getNameOfProduct() << " from the cell "
<< cells[index].getName() << " " << D.getDateString() << " " << D.getTimeString() << endl;
cells[index].deleteElement();
--totalProducts;
}
}
}
else cout << "\nInvalid value of cell name entered\nEnter the cell name from the list\n" << endl;
}
int Machine::getTotalProducts() const
{
return totalProducts;
}
const vector<Cell>& Machine::getCells() const
{
return cells;
}
const std::vector<Purchase>& Machine::getPurchasesHistory() const
{
return purchasesHistory;
}
| true |
6ba8eef0493b475ecfadfb7a7cc7a92e2a2ca77e | C++ | oboro-graph/Smart-Grid-Advanced-Metering-Infrastructure-privacy-preserving-protocol-implementation | /src/crypto/SmartMeter.h | UTF-8 | 3,292 | 2.796875 | 3 | [] | no_license | #ifndef __SMIMP_SMARTMETER_H_
#define __SMIMP_SMARTMETER_H_
#include "examples.h"
#include "Requester.h"
class SMAdapter;
namespace SMImp {
//! Smart Meter protocol implementation.
/*!
Most variables have been named after their respective names given in the original research paper available [here](https://www.researchgate.net/publication/305077004_Secure_and_efficient_protection_of_consumer_privacy_in_Advanced_Metering_Infrastructure_supporting_fine-grained_data_analysis). See section 5 (Page 7) for the beginning of the protocol implementation.
*/
class SmartMeter : public Requester
{
private:
//! Shared secrete with Utility Company for HMAC Verification.
Integer hmacKey;
//! Anonymous ID.
Integer anonId;
//! Session key shared with Trusted Thrid Party.
Integer sessionKey;
//! Verbose flag, used for debugging
bool verbose;
//! Pointer to adapter, only used for debugging
/*!
\sa Adapter::print(char*)
*/
::SMAdapter* out;
public:
/*!
\sa SMImp::Requester::Requester(Integer,SHA1)
*/
SmartMeter(Integer, CryptoPP::SHA1*);
/*!
For debugging.
*/
SmartMeter(Integer, ::SMAdapter*);
SmartMeter(Integer);
virtual ~SmartMeter();
/*!
Sets HMAC to be used for verification.
*/
void setHMACKey(Integer);
/*!
Generates keys from payload given by Utility Company.
*/
bool generateKeys(Payload);
/*!
Sets the anonymous ID
*/
void setAnonId(Integer);
/*!
\sa SMImp::Requester::getAnonId()
*/
Integer getAnonId();
/*!
Encrypts data to be sent to the Trusted Thrid Party.
\param data Data to be encrypted and sent to Trusted Thrid Party.
\return Packet of encrypted data.
*/
Packet* sendDataToTTP(Integer data);
/*!
Performs all the processes to both generate and split up the session key, returning an array of packets to encasulate in the Adapter.
\param m Message, or the session key to be generated, see SMAdaoter::startSessionKeyExchange(omnetpp::cMessage* msg).
\param l Length of the session key, does not need to be a multiple of 4 since char('0')s (or int(48)) are padded to reach the desired length.
\param trustedPartyId ID of the Trusted Third Party to share a session key with.
\param trustedPartyKey Missnamed variable, this is just the first piece of the public key - specificially the component generated by the Utility Company.
\param trustedPartyMu second peice of the public key, generated by the Trusted Third Party.
\return Returns array of messages to be encapsulated and sent to Trusted Third Party. Array is of length (l+(4-(l%4)))/4, or ceiling(l/4) where l is the length of the session key.
*/
Packet* sessionKeyExchange(char* m,Integer l,Integer trustedPartyId, Integer trustedPartyKey, Integer trustedPartyMu);
/*!
Used at the end of the session key exchange phase. HMAC verifies, then decrypts the final shared session key.
\param c1 Part 1 of the encrypted session key.
\param c2 Part 2 of the encrypted session key.
\param ttpId ID of the Trusted Third Party.
*/
bool recieveHMAC(Integer c1, Integer c2, Integer ttpId);
};
};
#endif
| true |
bbb8d738adc50e1af0f30905e6387c7fea652fad | C++ | NirvanaNimbusa/better-faster-stronger-mixer | /src/coverage.cpp | UTF-8 | 9,032 | 2.625 | 3 | [
"MIT"
] | permissive | #include "AllMixersWithClasses.h"
#include "bitops/rot.h"
#include "doctest.h"
#include "fmt/to_hex.h"
#include "robin_hood.h"
#include "sfc64.h"
#include <algorithm>
#include <bitset>
#include <iostream>
#include <nmmintrin.h>
uint16_t mumx16(uint16_t a, uint16_t b) {
auto m = static_cast<uint32_t>(a) * static_cast<uint32_t>(b);
m ^= m >> 16;
return static_cast<uint16_t>(m);
}
uint16_t muma16(uint16_t a, uint16_t b) {
auto m = static_cast<uint32_t>(a) * static_cast<uint32_t>(b);
m += m >> 16;
return static_cast<uint16_t>(m);
}
// 63.2199% coverage
uint32_t mumx32(uint32_t a, uint32_t b) {
auto m = static_cast<uint64_t>(a) * static_cast<uint64_t>(b);
m ^= m >> 32;
return static_cast<uint32_t>(m);
}
// 98.8868% coverage with prime 325117817
// 96.9752% prime 1766600701
// 76.0819% prime 4178408657
// 89.0185% coverage with UINT32_C(0x9E3779B1)
uint32_t muma32(uint32_t a, uint32_t b) {
auto m = static_cast<uint64_t>(a) * static_cast<uint64_t>(b);
return static_cast<uint32_t>(m) + static_cast<uint32_t>(m >> 32);
}
// 63,21% coverage
inline uint32_t mumxmumxx2_32(uint32_t v, uint32_t a, uint32_t b) {
return mumx32(mumx32(v, a), mumx32(v, b));
}
// 63.21% coverage:
inline uint32_t mumxmumxx3_32(uint32_t v, uint32_t, uint32_t b) {
v *= 325117817;
return (v ^ rotr(v, 13) ^ rotr(v ^ b, 23));
}
//////////////
// 48% coverage
inline uint16_t wyhash3_mix16(uint16_t v, uint16_t wyp0, uint16_t wyp1, uint16_t wyp4) {
uint16_t a = static_cast<uint16_t>(v & 0x00ff);
uint16_t b = static_cast<uint16_t>(v >> 8U);
return mumx16(mumx16(a ^ wyp0, b ^ wyp1), UINT16_C(8) ^ wyp4);
}
// 48.63% coverage
inline uint32_t wyhash3_mix32(uint32_t v, uint32_t wyp0, uint32_t wyp1, uint32_t wyp4) {
uint32_t a = static_cast<uint32_t>(v & 0x0000ffff);
uint32_t b = static_cast<uint32_t>(v >> 16U);
return mumx32(mumx32(a ^ wyp0, b ^ wyp1), UINT16_C(8) ^ wyp4);
}
// 39.34% coverage
inline uint32_t wyhash3_rand(uint32_t v, uint32_t wyp0) {
return mumx32(v ^ wyp0, v);
}
//////
// 100% coverage
inline uint32_t fmix32(uint32_t h) noexcept {
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
///////
// 74.69% coverage
inline uint32_t lemire_stronglyuniversal32(uint32_t x, uint32_t k1, uint32_t k2, uint32_t k3,
uint32_t k4, uint32_t k5, uint32_t k6) noexcept {
uint32_t lo = x & UINT32_C(0x0000ffff);
uint32_t hi = x >> 16;
uint32_t r1 = (k1 * lo + k2 * hi + k3) >> 16;
uint32_t r2 = (k4 * lo + k5 * hi + k6) >> 16;
return (r1 << 16) | r2;
}
// 100% coverage
inline uint32_t crc32(uint32_t v) noexcept {
return static_cast<uint32_t>(_mm_crc32_u64(0, v));
}
// 100% coverage
inline uint32_t xorshift(uint32_t h) noexcept {
h ^= h >> 2;
return h;
}
// 100% coverage
inline uint32_t xorshift2(uint32_t h, uint32_t a) noexcept {
return a ^ h ^ (h >> 17);
}
inline uint32_t rotrxx(uint32_t x) noexcept {
return x ^ rotr(x, 25) ^ rotr(x, 13);
}
// 50% coverage
inline uint32_t rotrx(uint32_t x) noexcept {
return x ^ rotr(x, 25);
}
//
inline uint32_t mumx_mumx_rrxx_1_32(uint32_t v) {
static constexpr auto a = UINT32_C(1766600701);
return muma32(v, a); // + (v ^ rotr(v, 4) ^ rotr(v ^ a, 17));
}
class Bitset {
public:
Bitset(size_t numBits)
: mData((numBits + 63) / 64) {}
void set(uint32_t idx) noexcept {
mData[idx >> 6] |= UINT64_C(1) << (idx & 0x3f);
}
bool setAndGet(uint32_t idx) noexcept {
auto& w64 = mData[idx >> 6];
auto mask = UINT64_C(1) << (idx & 0x3f);
bool isSet = (w64 & mask) != 0;
w64 |= mask;
return isSet;
}
void clear() {
std::memset(mData.data(), 0, mData.size() * 8);
}
void prefetchWrite(uint32_t idx) const noexcept {
__builtin_prefetch(mData.data() + (idx >> 6), 1, 0);
}
size_t count() const noexcept {
size_t s = 0;
for (auto d : mData) {
s += std::bitset<64>(d).count();
}
return s;
}
private:
std::vector<uint64_t> mData;
};
// real 0m42,976s
// real 0m39,125s prefetch 16
// prefetch idea from
// https://encode.su/threads/3207-ZrHa_update-a-fast-construction-for-iterated-hashing code
// https://gist.github.com/svpv/c305e63110dfc4ab309ad7586ceea277
TEST_CASE("coverage" * doctest::skip()) {
// can't allocate bitset on the stack => segfault
static constexpr size_t Size = UINT64_C(1) << 32;
// auto bits = new std::bitset<Size>();
auto bits = Bitset(Size);
sfc64 rng(1234);
#if 0
auto k1 = static_cast<uint32_t>(rng() | 1);
auto k2 = static_cast<uint32_t>(rng() | 1);
auto k3 = static_cast<uint16_t>(rng() | 1);
auto k4 = static_cast<uint32_t>(rng() | 1);
auto k5 = static_cast<uint32_t>(rng() | 1);
auto k6 = static_cast<uint16_t>(rng() | 1);
#endif
std::array<uint32_t, 64> tmp;
tmp.fill(mumx32(0, 0x7849ae79));
for (size_t i = 0; i < Size; ++i) {
bits.set(tmp[i % tmp.size()]);
auto v = mumx32(i, 0x7849ae79);
bits.prefetchWrite(v);
tmp[i % tmp.size()] = v;
}
for (auto v : tmp) {
bits.set(v);
}
auto ratio = (100.0 * static_cast<double>(bits.count()) / static_cast<double>(Size));
std::cout << ratio << "% coverage (" << bits.count() << " of " << Size << ")" << std::endl;
}
TEST_CASE("coverage_optimizer" * doctest::skip()) {
static constexpr size_t Size = UINT64_C(1) << 32;
sfc64 rng;
auto bits = Bitset(Size);
while (true) {
auto k = static_cast<uint32_t>(rng() | 1);
std::array<uint32_t, 64> tmp;
for (size_t i = 0; i < 64; ++i) {
tmp[i] = mumx32(i, k);
}
size_t i = 64;
for (; i < Size; ++i) {
if (bits.setAndGet(tmp[i % tmp.size()])) {
break;
}
auto v = mumx32(i, k);
bits.prefetchWrite(v);
tmp[i % tmp.size()] = v;
}
auto ratio = (100.0 * static_cast<double>(bits.count()) / static_cast<double>(Size));
std::cout << std::dec << i << " for " << std::hex << "UINT32_C(0x" << k << "). " << std::dec
<< ratio << "% coverage (" << bits.count() << " of " << Size << ")" << std::endl;
bits.clear();
}
}
TEST_CASE("coverage_optimizer16" * doctest::skip()) {
static constexpr size_t Size = UINT64_C(1) << 16;
sfc64 rng;
auto bits = Bitset(Size);
std::vector<std::pair<size_t, size_t>> data;
for (size_t k = 0; k < Size; ++k) {
bits.clear();
for (size_t i = 0; i < Size; ++i) {
bits.set(muma16(i, k));
}
// auto ratio = (100.0 * static_cast<double>(bits.count()) / static_cast<double>(Size));
data.emplace_back(bits.count(), k);
}
std::sort(data.begin(), data.end());
for (size_t i = 0; i < data.size(); ++i) {
// std::cout << data[i].first << " " << std::bitset<16>(data[i].second) << std::endl;
std::cout << data[i].first << std::endl;
}
}
uint64_t dummyhash(uint64_t x) {
uint64_t h;
umul128(x, UINT64_C(0xa0761d6478bd642f), &h);
return h;
}
TEST_CASE("find_collisions" * doctest::skip()) {
auto mask = UINT64_C(0xfffFFFFF);
uint64_t x = 0;
uint64_t pre = 0;
while (true) {
auto h = robin_hood_hash_int(x);
// auto h = wyhash3_mix(x);
if (0 == (h & mask)) {
std::cout << x << " " << (x - pre) << " -> " << to_hex(h) << std::endl;
pre = x;
}
x += 4056985630;
}
}
TEST_CASE("collisions" * doctest::skip()) {
std::vector<size_t> vec(1U << 20);
auto mask = vec.size() - 1;
for (size_t i = 0; i < 100000000; ++i) {
auto x = i << 35;
// auto h = robin_hood_hash_int(x);
auto h = dummyhash(x);
// auto h = mumx_mumx_rrxx_1(x);
// auto h = nasam(x);
// auto h = i * UINT64_C(0xa0761d6478bd642f);
++vec[h & mask];
}
std::sort(vec.begin(), vec.end());
size_t count = 100;
for (size_t i = 0; i <= count; ++i) {
auto idx = (vec.size() - 1) * i / count;
std::cout << vec[idx] << std::endl;
}
}
TEST_CASE("coverage64" * doctest::skip()) {
// can't allocate bitset on the stack => segfault
robin_hood::unordered_flat_map<uint32_t, uint8_t> map;
auto bits = Bitset(UINT64_C(1) << 32);
uint64_t x = 0;
while (true) {
// 1598982049 nasam
// 1598925211 mumx_mumx_rrxx_1
// 1767169350 robin_hood_hash_int
for (size_t i = 0; i < 1000000000; ++i) {
auto h = robin_hood_hash_int(x);
// auto h = mumx_mumx_rrxx_1(x);
// auto h = nasam(x);
bits.set(static_cast<uint32_t>(h));
bits.set(static_cast<uint32_t>(h >> 32));
++x;
}
std::cout << bits.count() << std::endl;
bits.clear();
}
} | true |
6fb4cf3b574fd311995fd5c4434bc969533ee051 | C++ | shoaibrayeen/Data-Structures-and-Algorithms | /DATA STRUCTURES/Array/Query Square Root Decomposition/code_1.cpp | UTF-8 | 1,075 | 3.46875 | 3 | [
"MIT"
] | permissive | //
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
struct Query {
int L, R;
};
void getQuerySums( vector<int> array , vector<Query> List ) {
int m = int(List.size());
for (int i = 0; i < m; i++) {
int L = List[i].L, R = List[i].R;
int sum = 0;
for (int j = L; j <= R; j++) {
sum += array[j];
}
cout << "\nSum of [" << L << ", " << R << "]\t:\t" << sum << endl;
}
}
int main() {
int size;
cout << "\nEnter Size of Array\t:\t";
cin >> size;
vector<int> array(size);
cout << "\nEnter Array Elements\n";
for ( int i = 0; i < size; i++ ) {
cin >> array[i];
}
cout << "\nEnter Number of Queries\t:\t";
cin >> size;
vector<Query> List(size);
cout << "\nEnter Queries (L,R) Form\n";
for ( int i = 0; i < size; i++ ) {
cin >> List[i].L;
cin >> List[i].R;
}
getQuerySums(array,List);
return 0;
}
| true |
c699335a1f1c8f8f4a8efe64dd925d398fc8fdf3 | C++ | whutaihejin/repo | /primer/chapter16/t16.2.cc | UTF-8 | 2,264 | 3.765625 | 4 | [] | no_license | #include <iostream>
template <typename T>
T Fobject(T x, T) {
return x;
}
template <typename T>
T Frefrence(const T& x, const T&) {
return x;
}
template <typename T>
int Compare(const T& x, const T& y) {
if (x < y) {
return -1;
} else if (y < x) {
return 1;
}
return 0;
}
template <typename T> void Fun1(T& x) {
std::cout << x << std::endl;
// T a = "std";
}
template <typename T> void Fun2(const T& x) {
std::cout << x << std::endl;
// error: cannot initialize a variable of type 'int' with an lvalue of type 'const char [4]'
// T a = "std";
}
template <typename T> void Fun3(T&& x) {
std::cout << x << std::endl;
T val = x;
val = 111;
if (val == x) {
std::cout << "val=" << val << " == " << "x=" << x << std::endl;
} else {
std::cout << "val=" << val << " != " << "x=" << x << std::endl;
}
// error: cannot initialize a variable of type 'int' with an lvalue of type 'const char [4]'
// error: non-const lvalue reference to type 'int' cannot bind to a value of unrelated type 'const char [4]'
// int val = 2;
// T a = val;
}
int main() {
int it = 1;
// note: in instantiation of function template specialization 'Fun3<int &>' requested here
Fun3(it);
Fun3(33);
std::string s1("a value");
const std::string s2("another value");
Fobject(s1, s2);
Frefrence(s1, s2);
//
int a[10] = {0};
int b[20] = {0};
Fobject(a, b);
// candidate template ignored: deduced conflicting types for parameter 'T' ('int [10]' vs. 'int [20]')
// Frefrence(a, b);
//
long x = 11L;
// note: candidate template ignored: deduced conflicting types for parameter 'T' ('long' vs. 'int')
// Compare(x, 22);
Compare<long>(x, 22);
//
int i = 1;
const int ci = 2;
Fun1(i); // int
Fun1(ci); // const int
// candidate function [with T = int] not viable: expects an l-value for 1st argument
// Fun1(3);
Fun2(i); // int
Fun2(ci); // int
Fun2(3); // int
int&& xxxx = 2;
int& yyyy = xxxx;
// non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
// int& yyyy = 3;
//
Fun3(3); // int
return 0;
}
| true |
ad126fafcd220b47170564a3b12ecff4e252e135 | C++ | xinfushe/gpu-real-time-shadows | /modelLoader.cpp | UTF-8 | 4,210 | 2.71875 | 3 | [] | no_license | #include "modelLoader.h"
#include <cassert>
#include <stdexcept>
#include <sstream>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <glm/glm.hpp>
std::ostream& operator<<(std::ostream& stream, const aiVector3D& vec)
{
stream << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return stream;
}
glm::vec3 aiToGlm(const aiVector3D& vector)
{
return glm::vec3(vector.x, vector.y, vector.z);
}
Vertex::Vertex(
float x, float y, float z,
float nx, float ny, float nz,
float u, float v):
_x(x),
_y(y),
_z(z),
_nx(nx),
_ny(ny),
_nz(nz),
_u(u),
_v(v)
{}
SimpleVertex::SimpleVertex(
float x, float y, float z):
_x(x),
_y(y),
_z(z)
{}
ModelInfo loadModel(
const std::string& filename,
std::vector<Vertex>& vertices,
std::vector<GLuint>& indices)
{
unsigned int indexOffset = vertices.size();
unsigned int baseIndex = indices.size();
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices );
if (!scene)
{
throw std::runtime_error("Nepodařilo se přečíst model");
}
if (scene->mNumMeshes != 1)
{
throw std::runtime_error("Jsou podporovány pouze modely s počtem meshů = 1");
}
const aiMesh* mesh = scene->mMeshes[0];
if (!mesh->HasFaces())
throw std::runtime_error("Mesh musí mít facy");
if (!mesh->HasPositions())
throw std::runtime_error("Mesh musí mít pozice");
if (!mesh->HasNormals())
throw std::runtime_error("Mesh musí mít normály");
if (!mesh->HasTextureCoords(0))
throw std::runtime_error("Mesh musí mít tex coordy");
if (mesh->GetNumUVChannels() != 1)
{
std::stringstream ss;
ss << "Mesh musí mít jeden UV kanál, ne " << mesh->GetNumUVChannels() << " kanálů";
throw std::runtime_error(ss.str());
}
vertices.reserve(vertices.size() + mesh->mNumVertices);
// Prevedeme vertexy
for (unsigned i = 0; i < mesh->mNumVertices; i++)
{
auto position = mesh->mVertices[i];
auto normal = aiToGlm(mesh->mNormals[i]);
auto uvw = mesh->mTextureCoords[0][i];
vertices.push_back(Vertex(
position.x,
position.y,
position.z,
normal.x,
normal.y,
normal.z,
uvw.x,
uvw.y));
}
indices.reserve(indices.size() + mesh->mNumFaces * 3);
// Prevedeme indexy
for (unsigned i = 0; i < mesh->mNumFaces; i++)
{
const aiFace face = mesh->mFaces[i];
if (face.mNumIndices != 3)
{
throw std::runtime_error("Jsou podporovány pouze facy se třemi body");
}
for (unsigned j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j] + indexOffset);
}
}
return ModelInfo {baseIndex, mesh->mNumFaces * 3};
}
ModelInfo loadSimpleModel(
const std::string& filename,
std::vector<SimpleVertex>& vertices,
std::vector<GLuint>& indices)
{
unsigned int indexOffset = vertices.size();
unsigned int baseIndex = indices.size();
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices );
if (!scene)
{
throw std::runtime_error("Nepodařilo se přečíst model");
}
if (scene->mNumMeshes != 1)
{
throw std::runtime_error("Jsou podporovány pouze modely s počtem meshů = 1");
}
const aiMesh* mesh = scene->mMeshes[0];
if (!mesh->HasFaces())
throw std::runtime_error("Mesh musí mít facy");
if (!mesh->HasPositions())
throw std::runtime_error("Mesh musí mít pozice");
vertices.reserve(vertices.size() + mesh->mNumVertices);
// Prevedeme vertexy
for (unsigned i = 0; i < mesh->mNumVertices; i++)
{
auto position = mesh->mVertices[i];
vertices.push_back(SimpleVertex(
position.x,
position.y,
position.z));
}
indices.reserve(indices.size() + mesh->mNumFaces * 3);
// Prevedeme indexy
for (unsigned i = 0; i < mesh->mNumFaces; i++)
{
const aiFace face = mesh->mFaces[i];
if (face.mNumIndices != 3)
{
throw std::runtime_error("Jsou podporovány pouze facy se třemi body");
}
for (unsigned j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j] + indexOffset);
}
}
return ModelInfo {baseIndex, mesh->mNumFaces * 3};
}
| true |
2299651ad429dd62e1ce3033e8a26c441fd53df8 | C++ | ellyheetov/Problem-Solving | /LeetCode/c++/300_Longest_Increasing_Subsequence.cpp | UTF-8 | 775 | 3.3125 | 3 | [] | no_license | //
// Created by 박혜원 on 2020/04/06.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> length_dp;
int max_length = 1;
int lengthOfLIS(vector<int>& nums) {
if(nums.size() == 0)
return 0;
length_dp.resize(nums.size(),1);
for(int i =1; i< nums.size(); i++){
for(int j =0; j < i; j++){
if(nums[j] < nums[i]){
length_dp[i] = max(1+ length_dp[j],length_dp[i]);
max_length = max(max_length, length_dp[i]);
}
}
}
return max_length;
}
};
int main(){
vector<int> nums ={ 1,3,6,7,9,4,10,5,6};
int ret = Solution().lengthOfLIS(nums);
cout << ret;
}
| true |
f17725df8f067ebc54ee7f142805bfe639b9554d | C++ | gudonghee2000/Algorithm-C | /BaekJoon/BaekJoon_재귀/10870.cc | UTF-8 | 256 | 2.84375 | 3 | [] | no_license | #include <iostream>
#define MAX 10000
using namespace std;
int fib(int n){
if(n==1)return 1;
if(n==0)return 0;
return fib(n-1)+fib(n-2);
}
int main() {
int n;
scanf("%d",&n);
int b= fib(n);
printf("%d",b);
return 0;
} | true |
f323dd2d9adf71395f7e7cf812b5b0708015c45b | C++ | Gazella019/Leetcode | /leetcode_1048.cpp | UTF-8 | 1,129 | 3.046875 | 3 | [] | no_license |
class Solution {
public:
int longestStrChain(vector<string>& words) {
int i, j, k, n, res = 0;
n = words.size();
vector<vector<int>> length(17);
vector<vector<int>> table(n, vector<int>(26, 0));
vector<int> dp(n, 1);
for(i=0;i<words.size();i++){
length[words[i].size()].push_back(i);
for(j=0;j<words[i].size();j++){
table[i][words[i][j]-'a'] += 1;
}
}
for(i=1;i<length.size();i++){
for(j=0;j<length[i].size();j++){
for(k=0;k<length[i-1].size();k++){
if(canChian(table[length[i][j]], table[length[i-1][k]])){
dp[length[i][j]] = max(dp[length[i][j]], dp[length[i-1][k]]+1);
}
}
res = max(res, dp[length[i][j]]);
}
}
for(i=0;i<dp.size();i++){
cout << dp[i] << " ";
}
return res;
}
bool canChian(vector<int>& a, vector<int>& b){
int i, diff = 0;
for(i=0;i<26;i++){
diff += abs(a[i]-b[i]);
}
if(diff == 1)
return true;
return false;
}
}; | true |
2694dacfb0bb964f2d7f0d1857525694ae008130 | C++ | MatthewBerkvens/Computer-Graphics-Engine | /Figure.cc | UTF-8 | 2,710 | 2.90625 | 3 | [] | no_license | #include "Figure.h"
Figure::Figure(std::vector<double>& _ambientReflection, std::vector<double>& _diffuseReflection, std::vector<double>& _specularReflection, double _reflectionCoefficient)
: ambientReflection(_ambientReflection), diffuseReflection(_diffuseReflection), specularReflection(_specularReflection), reflectionCoefficient(_reflectionCoefficient)
{
assert(_ambientReflection.size() == 3);
assert(_diffuseReflection.size() == 3);
assert(_specularReflection.size() == 3);
}
std::pair<std::vector<Point2D>, std::vector<Line2D>> projectFigures(std::vector<Figure>& figures, const double d)
{
std::vector<Line2D> lines;
std::vector<Point2D> points;
for (std::vector<Figure>::iterator it_figure = figures.begin(); it_figure != figures.end(); ++it_figure)
{
Color color = colorFromNormalizedDoubleTuple(it_figure->ambientReflection);
for (std::vector<Face>::iterator it_face = it_figure->faces.begin(); it_face != it_figure->faces.end(); ++it_face)
{
for (std::vector<int>::size_type i = 0; i != it_face->point_indexes.size(); i++)
{
Vector3D a_vec;
Vector3D b_vec;
if (i == it_face->point_indexes.size() - 1) {
if (it_face->point_indexes.size() > 2)
{
a_vec = it_figure->points[it_face->point_indexes[i]];
b_vec = it_figure->points[it_face->point_indexes[0]];
assert(it_face->point_indexes[i] != it_face->point_indexes[0]);
}
else continue;
}
else
{
a_vec = it_figure->points[it_face->point_indexes[i]];
b_vec = it_figure->points[it_face->point_indexes[i + 1]];
assert(it_face->point_indexes[i] != it_face->point_indexes[i + 1]);
}
Point2D a_pt = projectPoint(a_vec, d);
Point2D b_pt = projectPoint(b_vec, d);
points.push_back(a_pt);
points.push_back(b_pt);
lines.push_back(Line2D(a_pt, a_vec.z, b_pt, b_vec.z, color));
}
}
}
return std::pair<std::vector<Point2D>, std::vector<Line2D>>(points, lines);
}
void combineFigures(Figure& out, std::vector<Figure>& figures)
{
out.points = {};
out.faces = {};
for (std::vector<Figure>::iterator it_figure = figures.begin(); it_figure != figures.end(); it_figure++)
{
unsigned int offset = out.points.size();
for (std::vector<Face>::iterator it_face = it_figure->faces.begin(); it_face != it_figure->faces.end(); it_face++)
{
Face newFace;
for (std::vector<unsigned int>::iterator it_face_pt_index = it_face->point_indexes.begin(); it_face_pt_index != it_face->point_indexes.end(); it_face_pt_index++)
{
newFace.point_indexes.push_back(*it_face_pt_index + offset);
}
out.faces.push_back(newFace);
}
out.points.insert(out.points.end(), it_figure->points.begin(), it_figure->points.end());
}
} | true |
47dc4e728a3ef3f8c21b2f2b1b9c6f326eea8abe | C++ | brosell/HTS-Games | /BertsToolBox/null_ostreambuf.h | UTF-8 | 381 | 2.875 | 3 | [] | no_license | #ifndef null_ostreambuf_h
#define null_ostreambuf_h
#include <iostream>
namespace hts
{
/** eats all output */
template <typename charT, typename traits = std::char_traits<charT> >
class null_ostreambuf: public std::basic_streambuf<charT, traits>
{
public:
protected:
virtual int_type overflow(int_type c)
{
return traits::not_eof(c);
}
};
}
#endif | true |
c0cf7429e495d6493c520d43a6084d2f3e9f4bf9 | C++ | AnthonyDugarte/competitive-programming | /COJ/3425.cpp | UTF-8 | 541 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
size_t t;
cin >> t;
while(--t != -1)
{
size_t n;
cin >> n;
string s;
map<string, size_t> counts;
while(--n != -1)
{
cin >> s >> s;
++counts[s];
}
size_t total_combs{ 0 };
for(auto & it : counts)
total_combs += total_combs * it.second + it.second;
cout << total_combs << "\n";
}
return 0;
} | true |
7aa3df5869fe6ae443ef0732d0c6ccfa912aeab2 | C++ | xMijumaru/CSC17A_Summer2018 | /CSC 17A CLASS/CSC 17A Assignment 1/Gaddis_8thEdition_CHAP8_ ProgChal7_LotteryWinner/main.cpp | UTF-8 | 1,376 | 3.484375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: kevr1
*
* Created on June 20, 2018, 6:11 PM
*/
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
//Function Prototypes
bool linear(int [], int, int);
int main(int argc, char** argv) {
//Declare all Variables Here
int lottery;//The weeks winning numbers that the user will input
int size=10;// Size that will be passed on during the search
const int num=10;//The 10 numbers that are inputted
int array[num]={13579, 26791, 26792, 33445, 55555,
62483, 77777, 79422, 85647, 93121};//the numbers to compare to
bool results;
//Input or initialize values Here
cout << "Enter the five winning lottery numbers (exclude spaces): ";
cin>>lottery;
results=linear(array, 10, lottery);
if (results==true)
{
cout << "You won the lottery " << endl;
}
if(results==false){
cout << "You did not win the lottery " << endl;
}
return 0;
}
bool linear (int array[], int num, int lottery)
{
for (int x=0;x<num;x++){
if (lottery==array[x]){
return true;
}
}
return false;
}
| true |