Skip to main content
Loading...

More C++ Posts

//Leif Messinger
//Finds all sets of 5 5 letter words that don't have duplicate letters in either themselves or each other.
//First it reads the words in and puts them in groups of their bitmasks
//After that, we recurse on each group. Before doing that, we remove the group from the set of other groups to check it against.
#include <cstdio> //getchar, printf
#include <cassert> //assert
#include <vector>
#include <set>
#include <algorithm> //std::copy_if
#include <iterator> //std::back_inserter

#define CHECK_FOR_CRLF true
#define MIN_WORDS 5
#define MAX_WORDS 5
#define WORD_TOO_LONG(len) (len != 5)

const unsigned int charToBitmask(const char bruh){
	assert(bruh >= 'a' && bruh <= 'z');
	return (1 << (bruh - 'a'));
}

void printBitmask(unsigned int bitmask){
	char start = 'a';
	while(bitmask != 0){
		if(bitmask & 1){
			putchar(start);
		}

		bitmask >>= 1;
		++start;
	}
}

//Pointer needs to be deleted
const std::set<unsigned int>* getBitmasks(){
	std::set<unsigned int>* bitmasksPointer = new std::set<unsigned int>;
	std::set<unsigned int>& bitmasks = (*bitmasksPointer);

	unsigned int bitmask = 0;
	unsigned int wordLength = 0;
	bool duplicateLetters = false;
	for(char c = getchar(); c >= 0; c = getchar()){
		if(CHECK_FOR_CRLF && c == '\r'){
			continue;
		}
		if(c == '\n'){
			if(!(WORD_TOO_LONG(wordLength) || duplicateLetters)) bitmasks.insert(bitmask);
			bitmask = 0;
			wordLength = 0;
			duplicateLetters = false;
			continue;
		}
		if((bitmask & charToBitmask(c)) != 0) duplicateLetters = true;
		bitmask |= charToBitmask(c);
		++wordLength;
	}

	return bitmasksPointer;
}

void printBitmasks(const std::vector<unsigned int>& bitmasks){
	for(unsigned int bruh : bitmasks){
		printBitmask(bruh);
		putchar(','); putchar(' ');
	}
	puts("");
}

//Just to be clear, when I mean "word", I mean a group of words with the same letters.
void recurse(std::vector<unsigned int>& oldBitmasks, std::vector<unsigned int> history, const unsigned int currentBitmask){
	//If there's not enough words left
	if(oldBitmasks.size() + (-(history.size())) + (-MIN_WORDS) <= 0){
		//If there's enough words
		if(history.size() >= MIN_WORDS){
			//Print the list
			printBitmasks(history);
		}
		return;
	//To make it faster, we can stop it after 5 words too
	}else if(history.size() >= MAX_WORDS){
		//Print the list
		printBitmasks(history);
		return;
	}

	//Thin out the array with only stuff that matches the currentBitmask.
	std::vector<unsigned int> newBitmasks;
	std::copy_if(oldBitmasks.begin(), oldBitmasks.end(), std::back_inserter(newBitmasks), [&currentBitmask](unsigned int bruh){
		return (bruh & currentBitmask) == 0;
	});

	while(newBitmasks.size() > 0){
		//I know this modifies 'oldBitmasks' too. It's intentional.
		//This makes it so that the word is never involved in any of the child serches or any of the later searches in this while loop.
		const unsigned int word = newBitmasks.back(); newBitmasks.pop_back();

		std::vector<unsigned int> newHistory = history;
		newHistory.push_back(word);

		recurse(newBitmasks, newHistory, currentBitmask | word);
	}
}

int main(){
	const std::set<unsigned int>* bitmasksSet = getBitmasks();
	std::vector<unsigned int> bitmasks(bitmasksSet->begin(), bitmasksSet->end());
	delete bitmasksSet;

	recurse(bitmasks, std::vector<unsigned int>(), 0);

	return 0;
}
//Get data file at https://codecatch.net/post.php?postID=91e87d73
//Iteration 1 of Wing Project. Solution breaks down around n=35

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
using namespace std;

int getSum(map<int, int> list);
void readData(map<int, float>* data);
void lowestPrice();
void findSums(int n, vector<map<int, int>>* sumsList, map<int, float>* data);
//void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList);
void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList, map<int, float>* data);
float getPrice(map<int, int> set, map<int, float>* data);

template <typename S>
ostream& operator<<(ostream& os, const vector<S>& vector)
{
	// Printing all the elements using <<
	for (auto element : vector) {
	os << element << " ";
	}
	return os;
}

bool operator==(map<int, int> m1, map<int, int> m2)
{
	if(m1.size() != m2.size())
	return false;

	bool ret = true;

	for(auto it = m1.begin(); it !=m1.end() && ret; it++)
	{
	if(ret && m1.count(it->first) != m2.count(it->first))
	ret = false;

	if(ret && m1.count(it->first) == 1)
	{
	if(m1.at(it->first) != m2.at(it->first))
	ret = false;
	}
	}

	return ret;
}


int main()
{
	map<int, float> data;
	readData(&data);

	vector<map<int, int>> *sumsList;
	sumsList = new vector<map<int, int>>;
	findSums(40, sumsList, &data);

	for(auto el : *sumsList)
	{
	for(auto it = el.begin(); it != el.end(); it++)
	{
	cout << it->first << "->" << it->second << " ";
	}
	cout << getPrice(el, &data) << endl;
	}

	return 0;
}

/* Returns the price of wings given a set of numbers of wings to buy.
	* Returns -1 if the set contains a number that is not possible to buy.
	*/
float getPrice(map<int, int> set, map<int, float>* data)
{
	float price = 0;
	for(auto it = set.begin(); it != set.end(); it++)
	{
	//If data doesn't contain an element of set, return -1
	if(data->count(it->first) == 0)
	return -1;
	
	price += data->at(it->first) * it->second; //pricePerPacket * qtyOfPackets
	}

	return price;
}

/* Adds the elements of list.
	* Suppose mapping is <num, qty>.
	* Returns sum(num*qty)
	*/
int getSum(map<int, int> list)
{
	int sum = 0;
	for(auto it = list.begin(); it != list.end(); it++)
	sum += it->first * it->second;
	return sum;
}

void findSums(int n, vector<map<int, int>>* sumsList, map<int, float>* data)
{
	map<int, int> currList;

	//Recur when currSum < n
	auto it = data->begin();
	while(it->first <= n && it != data->end())
	{
	findSum(currList, it->first, n, sumsList, data);
	it++;
	}
}

void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList, map<int, float>* data)
{
	//Append x to currList
	if(currList.count(x) == 0)
	currList.emplace(x, 1);
	else
	{
	int val = 1+ currList.at(x);
	currList.erase(x);
	currList.emplace(x, val);
	}

	//Determine current sum, check for return cases
	int currSum = getSum(currList);

	if(currSum > n)
	return;
	else if(currSum == n)
	{

	//Check to make sure no duplicates
	for(auto list : *sumsList)
	{
	if(list == currList)
	return;
	}

	sumsList->push_back(currList);
	return;
	}

	//Recur when currSum < n
	auto it = data->begin();
	while(it->first <= n-x && it != data->end())
	{
	findSum(currList, it->first, n, sumsList, data);
	it++;
	}
}

void readData(map<int, float>* data)
{
	ifstream file ("./data", ifstream::in);

	if(file.is_open())
	{
	int i = 0;
	while(!file.eof())
	{
	float wings, price;
	string skipnl;
	file >> wings;
	file >> price;

	data->emplace(wings, price);

	getline(file, skipnl);
	i++;
	}
	}
}
/*
Good morning! Here's your coding interview problem for today.

This problem was asked by LinkedIn.

A wall consists of several rows of bricks of various integer lengths and uniform height. Your goal is to find a vertical line going from the top to the bottom of the wall that cuts through the fewest number of bricks. If the line goes through the edge between two bricks, this does not count as a cut.

For example, suppose the input is as follows, where values in each row represent the lengths of bricks in that row:

[[3, 5, 1, 1],
	[2, 3, 3, 2],
	[5, 5],
	[4, 4, 2],
	[1, 3, 3, 3],
	[1, 1, 6, 1, 1]]

The best we can we do here is to draw a line after the eighth brick, which will only require cutting through the bricks in the third and fifth row.

Given an input consisting of brick lengths for each row such as the one above, return the fewest number of bricks that must be cut to create a vertical line.

AUTHORS NOTE:
Makes following assumptions:
- Each row is same length
- Data is in file called "data.dat" and formatted in space-separated rows
- The cuts at the beginning and end of the wall are not solutions

This requires the following file named data.dat that is a space separated file, or similar formatted file:
----START FILE----
3 5 1 1
2 3 3 2
5 5
4 4 2
1 3 3 3
1 1 6 1 1
----END FILE----
*/

#include <algorithm>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	vector<vector<int>> wall;

	ifstream in;
	in.open("data.dat");
	if(!in.good())
	{
	cout << "ERROR: File failed to open properly.\n";
	}

	/* Get input from space separated file */
	string line;
	while(!in.eof())
	{
	getline(in, line);

	int i;
	vector<int> currv;
	stringstream strs(line);
	while(strs >> i)
	currv.push_back(i);
	wall.push_back(currv);
	}

	

	/* Convert each value from "length of brick" to "position at end of brick" */
	for(int y = 0; y < wall.size(); y++)
	{
	wall.at(y).pop_back(); //Delet last val
	for(int x = 1; x < wall.at(y).size(); x++) //Skip the first bc data doesn't need change
	wall.at(y).at(x) += wall.at(y).at(x-1);
	}

	/* Check output. COMMENT OUT */
	// for(auto row : wall)
	// {
	// for(int pos : row)
	// cout << pos << " ";
	// cout << endl;
	// }

	/* Determine which ending position is most common, and cut there */
	//Exclude final position, which will be the size of the wall

	int mode = -1;
	int amt = -1;
	vector<int> tried;
	for(auto row : wall)
	{
	for(int pos : row) //For each pos in the wall
	{
	//Guard. If pos is contained in the list, skip pos
	if(find(tried.begin(), tried.end(), pos) != tried.end())
	continue;
	tried.push_back(pos);

	/* Cycle through each row to see if it contains the pos */
	int curramt = 0;
	for(auto currrow : wall)
	{
	if( find( currrow.begin(), currrow.end(), pos ) != currrow.end() )
	curramt++;
	}
	//cout << pos << " " << curramt << endl; 

	if(curramt > amt)
	{
	amt = curramt;
	mode = pos;
	}
	}
	}

	cout << "Please cut at position " << mode << endl;
	cout << "This will cut through " << (wall.size() - amt) << " bricks." << endl;

	return 0;
}
#include <iostream>
#include <vector>
#include <limits>

#define DEBUG_TRIAL false

class Trial{
    public:
        const size_t HEIGHT;
        std::string record;
        
        //Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
        //Eggs is the eggs remaining.
        //Start is the bottom floor.
        //End is one above the top floor.
        const size_t BREAKING_HEIGHT;
        size_t eggs;
        size_t start;
        size_t end;
        
        
        size_t floorsLeft(){
            return (end-start);
        }
        
        size_t middle(){
            return start + (floorsLeft()/2UL);
        }
        
        size_t drops = 0;
        Trial(const size_t BREAKING_HEIGHT, size_t eggs, size_t start, size_t end): BREAKING_HEIGHT(BREAKING_HEIGHT), eggs(eggs), start(start), end(end), HEIGHT(end), record(end, '_'){
            record[BREAKING_HEIGHT] = 'B'; //Marking the breaking point
        }
        
        bool foundAnswer(){
            return ((record[0] == 'X') || (record.find("OX")!=std::string::npos));
        }
        
        //returns true if the egg broke.
        //height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
        bool drop(size_t height){
            
            #if DEBUG_TRIAL
                std::cout << "Start: " << start << ". End: " << end << ". Floors Left: " << floorsLeft() << ". Middle Index: " << middle() << std::endl;
            #endif
            
            drops++;
            bool cracked = height >= BREAKING_HEIGHT;
            if(cracked) --eggs;
            
            //Update the record
            record[height] = (height >= BREAKING_HEIGHT)? 'X' : 'O';
            
            #if DEBUG_TRIAL
                //Print the record
                std::cout << record << std::endl;
            #endif
        
            return cracked;
        }
        
        size_t nowWhat(){
            if(foundAnswer()){
                return drops;
            }else if(eggs <= 0){ //Ran out of eggs
                throw "Algorithm failed! No more eggs!";
                return 1UL;
            }else if(eggs > 1){
                return wrecklessSearch();
            }else{
                return safeSearch();
            }
        }
        
        size_t safeSearch(){
            if(drop(start)){
                --end;
            }else{
                ++start;
            }
            
            return nowWhat();
        }
        
        size_t wrecklessSearch(){
            //If the egg breaks
            if(drop(middle())){
                end -= (floorsLeft()/2UL);
            }else{ //egg doesn't crack
                start += (floorsLeft()/2UL);
            }
            
            return nowWhat();
        }
        
        //returns the amount of drops needed to find the answer
        size_t search(){
            return nowWhat();
        }
};

//Height is the height of the building in floors.
//Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
//Eggs is the eggs given.
//returns the amount of drops needed to find the answer
size_t search(const size_t height, const size_t BREAKING_HEIGHT, size_t eggs){
    Trial trial(BREAKING_HEIGHT, eggs, 0, height);
    return trial.search();
}

class TrialStats {
    public:
        size_t min = std::numeric_limits<size_t>::max();
        size_t max = 0;
        double mean = -1.0;
        
        void printStats(){
            // Print the results
            std::cout << "Minimum drops: " << min << std::endl;
            std::cout << "Maximum drops: " << max << std::endl;
            std::cout << "Mean drops: " << mean << std::endl;
        }
};

//Benchmarks all the possible breaking points of a single building height with a number of eggs.
TrialStats trial(const size_t HEIGHT, const size_t eggs){
    
    TrialStats stats;
    int totaldrops = 0;

    //Test every possible breaking point
    //Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
    for (int breakingHeight = 0; breakingHeight < HEIGHT; ++breakingHeight) {
        size_t drops = search(HEIGHT, breakingHeight, eggs);

        stats.min = std::min(stats.min, drops);
        stats.max = std::max(stats.max, drops);
        totaldrops += drops;
    }

    // Calculate the mean number of drops
    stats.mean = static_cast<double>(totaldrops) / HEIGHT;
    
    return stats;
}

//Benchmarks a single building height from 1 egg to MAX_EGGS
void testTower(const size_t height, const size_t MAX_EGGS){
    //Drop every amount of eggs that you'd need.
    for (int eggs = 1; eggs <= MAX_EGGS; ++eggs) {
        std::cout << "Building height: " << height << ". Num eggs: " << eggs << std::endl;
        
        TrialStats stats = trial(height, eggs);
        stats.printStats();
        
        std::cout << std::endl << std::endl;
    }
}

//Benchmarks all buildings from 0 to MAX_HEIGHT
void benchmark(const size_t MAX_HEIGHT){
    const size_t MAX_EGGS = 2;
    //Test every building
    for (size_t height = 1; height <= MAX_HEIGHT; ++height) {
        testTower(height, std::min(height, MAX_EGGS));
    }
}

int main() {
    constexpr size_t MAX_HEIGHT = 36;
    
    benchmark(MAX_HEIGHT);

    return 0;
}