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;
}
//From https://create.arduino.cc/projecthub/abhilashpatel121/easyfft-fast-fourier-transform-fft-for-arduino-9d2677
#include <cmath>
#include <iostream>
const unsigned char sine_data[] = {	//Quarter a sine wave
	0, 
	4, 9, 13, 18, 22, 27, 31, 35, 40, 44, 
	49, 53, 57, 62, 66, 70, 75, 79, 83, 87, 
	91, 96, 100, 104, 108, 112, 116, 120, 124, 127, 
	131, 135, 139, 143, 146, 150, 153, 157, 160, 164, 
	167, 171, 174, 177, 180, 183, 186, 189, 192, 195, //Paste this at top of program
	198, 201, 204, 206, 209, 211, 214, 216, 219, 221, 
	223, 225, 227, 229, 231, 233, 235, 236, 238, 240, 
	241, 243, 244, 245, 246, 247, 248, 249, 250, 251, 
	252, 253, 253, 254, 254, 254, 255, 255, 255, 255
};
float sine(int i){	//Inefficient sine
	int j=i;
	float out;
	while(j < 0) j = j + 360;
	while(j > 360) j = j - 360;
	if(j > -1 && j < 91) out = sine_data[j];
	else if(j > 90 && j < 181) out = sine_data[180 - j];
	else if(j > 180 && j < 271) out = -sine_data[j - 180];
	else if(j > 270 && j < 361) out = -sine_data[360 - j];
	return (out / 255);
}

float cosine(int i){	//Inefficient cosine
	int j = i;
	float out;
	while(j < 0) j = j + 360;
	while(j > 360) j = j - 360;
	if(j > -1 && j < 91) out = sine_data[90 - j];
	else if(j > 90 && j < 181) out = -sine_data[j - 90];
	else if(j > 180 && j < 271) out = -sine_data[270 - j];
	else if(j > 270 && j < 361) out = sine_data[j - 270];
	return (out / 255);
}

//Example data:

//-----------------------------FFT Function----------------------------------------------//
float* FFT(int in[],unsigned int N,float Frequency){	//Result is highest frequencies in order of loudness. Needs to be deleted.
	/*
	Code to perform FFT on arduino,
	setup:
	paste sine_data [91] at top of program [global variable], paste FFT function at end of program
	Term:
	1. in[] : Data array, 
	2. N : Number of sample (recommended sample size 2,4,8,16,32,64,128...)
	3. Frequency: sampling frequency required as input (Hz)

	If sample size is not in power of 2 it will be clipped to lower side of number. 
	i.e, for 150 number of samples, code will consider first 128 sample, remaining sample will be omitted.
	For Arduino nano, FFT of more than 128 sample not possible due to mamory limitation (64 recomended)
	For higher Number of sample may arise Mamory related issue,
	Code by ABHILASH
	Contact: [email protected] 
	Documentation:https://www.instructables.com/member/abhilash_patel/instructables/
	2/3/2021: change data type of N from float to int for >=256 samples
	*/

	unsigned int sampleRates[13]={1,2,4,8,16,32,64,128,256,512,1024,2048};
	int a = N;
	int o;
	for(int i=0;i<12;i++){		//Snapping N to a sample rate in sampleRates
		if(sampleRates[i]<=a){
			o = i;
		}
	}
		 
	int in_ps[sampleRates[o]] = {}; //input for sequencing
	float out_r[sampleRates[o]] = {}; //real part of transform
	float out_im[sampleRates[o]] = {}; //imaginory part of transform
	int x = 0; 
	int c1;
	int f;
	for(int b=0;b<o;b++){ // bit reversal
		c1 = sampleRates[b];
		f = sampleRates[o] / (c1 + c1);
		for(int j = 0;j < c1;j++){ 
			x = x + 1;
			in_ps[x]=in_ps[j]+f;
		}
	}

	
	for(int i=0;i<sampleRates[o];i++){ // update input array as per bit reverse order
		if(in_ps[i]<a){
			out_r[i]=in[in_ps[i]];
		}
		if(in_ps[i]>a){
			out_r[i]=in[in_ps[i]-a];
		} 
	}


	int i10,i11,n1;
	float e,c,s,tr,ti;

	for(int i=0;i<o;i++){ //fft
		i10 = sampleRates[i]; // overall values of sine/cosine :
		i11 = sampleRates[o] / sampleRates[i+1]; // loop with similar sine cosine:
		e = 360 / sampleRates[i+1];
		e = 0 - e;
		n1 = 0;

		for(int j=0;j<i10;j++){
			c=cosine(e*j);
			s=sine(e*j); 
			n1=j;

			for(int k=0;k<i11;k++){
				tr = c*out_r[i10 + n1]-s*out_im[i10 + n1];
				ti = s*out_r[i10 + n1]+c*out_im[i10 + n1];

				out_r[n1 + i10] = out_r[n1]-tr;
				out_r[n1] = out_r[n1]+tr;

				out_im[n1 + i10] = out_im[n1]-ti;
				out_im[n1] = out_im[n1]+ti; 

				n1 = n1+i10+i10;
			} 
		}
	}

	/*
	for(int i=0;i<sampleRates[o];i++)
	{
	std::cout << (out_r[i]);
	std::cout << ("\t"); // un comment to print RAW o/p 
	std::cout << (out_im[i]); std::cout << ("i"); 
	std::cout << std::endl;
	}
	*/


	//---> here onward out_r contains amplitude and our_in conntains frequency (Hz)
	for(int i=0;i<sampleRates[o-1];i++){ // getting amplitude from compex number
		out_r[i] = sqrt(out_r[i]*out_r[i]+out_im[i]*out_im[i]); // to increase the speed delete sqrt
		out_im[i] = i * Frequency / N;
		std::cout << (out_im[i]); std::cout << ("Hz");
		std::cout << ("\t");	// un comment to print freuency bin 
		std::cout << (out_r[i]);
		std::cout << std::endl;
	}




	x = 0; // peak detection
	for(int i=1;i<sampleRates[o-1]-1;i++){
		if(out_r[i]>out_r[i-1] && out_r[i]>out_r[i+1]){
			in_ps[x] = i; //in_ps array used for storage of peak number
			x = x + 1;
		} 
	}


	s = 0;
	c = 0;
	for(int i=0;i<x;i++){ // re arraange as per magnitude
		for(int j=c;j<x;j++){
			if(out_r[in_ps[i]]<out_r[in_ps[j]]){
				s=in_ps[i];
				in_ps[i]=in_ps[j];
				in_ps[j]=s;
			}
		}
		c=c+1;
	}
	float* f_peaks = new float[sampleRates[o]];
	for(int i=0;i<5;i++){ // updating f_peak array (global variable)with descending order
		f_peaks[i]=out_im[in_ps[i]];
	}
	return f_peaks;
}

//------------------------------------------------------------------------------------//
//main.cpp
int data[64]={
14, 30, 35, 34, 34, 40, 46, 45, 30, 4, -26, -48, -55, -49, -37,
-28, -24, -22, -13, 6, 32, 55, 65, 57, 38, 17, 1, -6, -11, -19, -34, 
-51, -61, -56, -35, -7, 18, 32, 35, 34, 35, 41, 46, 43, 26, -2, -31, -50,
-55, -47, -35, -27, -24, -21, -10, 11, 37, 58, 64, 55, 34, 13, -1, -7
};

int main(){
	const unsigned int SAMPLE_RATE = 48*1000;	//48khz
	auto result = FFT(data,64,SAMPLE_RATE);
	std::cout << result[0] << " " << result[1] << " " << result[2] << " " << result[3] << std::endl;
	delete[] result;
	return 0;
}
#define NUM_BITS 8

#include <iostream>


struct Number{
    int num : NUM_BITS;
    Number(){}
    Number(const int& bruh){
        num = bruh;
    }
    operator int() const { return num; }
    Number& operator=(const int& bruh){
        num = bruh;
        return (*this);
    }
};

using namespace std;

bool isNegative(const int& num){
    //This gets the bitwise and of num and 10000000000000000000000000000000
    //This implicit casts to bool, which means (num & (1 << 31)) != 0
    return (num & (1 << 31));
}

void printBinaryNumber(const int& num, const int numBits){
    for(int i = numBits; i > 0; --i){
        //8..1
        int bitMask = 1 << (i-1);
        if(num & bitMask){ //Test the bit
            cout << '1';
        }else{
            cout << '0';
        }
    }
}

void printCarryBits(const int& a, const int& b, const int numBits){
    int answer = 0;
    
    bool carry = false;
    for(int i = 0; i < numBits; ++i){
        //8..1
        int bitMask = 1 << i;
        bool aBit = a & bitMask;
        bool bBit = b & bitMask;
        if(aBit && bBit || aBit && carry || bBit && carry){ //Carry bit is true next
            if(carry)
                answer |= bitMask;
            carry = true;
        }else{
            if(carry)
                answer |= bitMask;
            carry = false;
        }
    }
    printBinaryNumber(answer, 8);
}


void printBorrowBits(const int& a, const int& b, const int numBits){
    int answer = 0;
    
    bool carry = false;
    for(int i = 0; i < numBits; ++i){
        //8..1
        int bitMask = 1 << i;
        bool aBit = a & bitMask;
        bool bBit = b & bitMask;
        if((!(aBit ^ carry)) && bBit){ //Carry bit is true next
            if(carry)
                answer |= bitMask;
            carry = true;
        }else{
            if(carry)
                answer |= bitMask;
            carry = false;
        }
    }
    printBinaryNumber(answer, 8);
}

void doProblem(const int& a, const int& b, const char& sign, const int& result, const int& numBits){
    if(sign == '+'){
        cout << ' '; printCarryBits(a, b, numBits); cout << endl;
    }else{
        cout << ' '; printBorrowBits(a, b, numBits); cout << endl;
    }
    cout << ' '; printBinaryNumber(a, numBits); cout << endl;
    cout << sign; printBinaryNumber(b, numBits); cout << endl;
    cout << "----------" << endl;
    cout << ""; printBinaryNumber(result, numBits + 1); cout << " = " << result;
    cout << endl;
}

int main(){
    
    Number a = 0b110;
    Number b = 0b011;
    cout<< a << endl << b << endl;
    
    doProblem(a, b, '+', a + b, NUM_BITS);
    doProblem(a, b, '-', a - b, NUM_BITS);
    doProblem(-a, b, '+', -a + b, NUM_BITS);
    doProblem(a, b, '-', -a - b, NUM_BITS);
    

    return 0;
}