Maximum value of range of values in array (C++) - range

The array ampVal has 25600 integers inside it. I need to find the maximum value of each set of 1024 values in the array and store it in another array. However I'm not getting this part to work it only gives 21 values and a random number '1348410436'. ampVal is a dynamic array.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int main() {
ifstream miniProject;
int n = 0;
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
cout<<"File Located ! :D \nCounting Lines in file..." << endl;
while (miniProject) {
string lines;
getline(miniProject, lines);
n++;
}
cout << "Number of lines in file are: " << n << endl;
miniProject.close();
}
int *frNum = new int[n];
int *bitNum = new int[n];
int *ampVal = new int[n];
for (int i = 0; i < n;i++){
frNum[i] = 0;
bitNum[i] = 0;
ampVal[i] = 0;
}
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
int i = 0;
string frameNumber, bitNumber, amplitudeValue;
while (miniProject) {
(miniProject >> frameNumber >> bitNumber >> amplitudeValue);
stringstream(frameNumber) >> frNum[i];
stringstream(bitNumber) >> bitNum[i];
stringstream(amplitudeValue) >> ampVal[i];
i++;
}
}
miniProject.close();
int frameGroupStart = 0;
int frameGroupEnd = 1024;
int maxAmpVal = 0;
while (frameGroupEnd != 25600) {
for (int i = frameGroupStart; i < frameGroupEnd; i++) {
if (ampVal[i] >maxAmpVal) {
maxAmpVal = ampVal[i];
cout << maxAmpVal << endl;
}
}
frameGroupStart = frameGroupStart + 1024;
frameGroupEnd = frameGroupEnd + 1024;
}
getchar();
return 0;
}

I used an alternate approach and this gets the job done:
int bitGroupStart = 0;
int bitGroupEnd = 1024;
int arrayOfMaxAmpVal[25];
int frameNumMaxVal[25];
int maxAmpVal = 0;
for (int i = 0; i < 25; i++) {
for (int j = bitGroupStart; j < bitGroupEnd; j++) {
if (ampVal[j] > maxAmpVal) {
maxAmpVal = ampVal[j];
}
}
bitGroupStart = bitGroupStart + 1024;
bitGroupEnd = bitGroupEnd + 1024;
arrayOfMaxAmpVal[i] = maxAmpVal;
frameNumMaxVal[i] = i;
maxAmpVal = 0;
}

Related

Convert DEC to IP dart

I get a int32 : -1407942911 that I need to convert to a ip
I used this function:
_setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip >> 8;
}
return _strData.toString();
}
but I get the ip backwards: 1.127.20.172 instead of 172.20.127.1
I was trying to replicate this java code
public String longToIp(long ip) {
StringBuilder result = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
result.insert(0,Long.toString(ip & 0xff));
if (i < 3) {
sb.insert(0,'.');
}
ip = ip >> 8;
}
return result.toString();
}
Update
I solved the error
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}
You can do something like this:
import 'dart:io';
import 'dart:typed_data';
void main() {
print(getIpFromInt32Value(-1407942911)); // 172.20.127.1
}
String getIpFromInt32Value(int value) => InternetAddress.fromRawAddress(
(ByteData(4)..setInt32(0, value)).buffer.asUint8List())
.address;
This solved the error:
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}

libpqxx v12 - dynamically bind vector-values to prepared statement (alternative to invocation)

I would like to use prepared statements to insert thousands of rows at once into my postgres database. The data to insert is stored in a vector of structs.
By reading the answers to How to prepare statements and bind parameters in Postgresql for C++ I thought I found the way how to do it.
Unfortunately, the current version of libpqxx I am using doesn't support pqxx::prepare::invocation anymore and I wasn't able to find any alternative in the docs/internet.
The code I tried out for my purpose is the following:
//pqxx header
#include "pqxx/connection.hxx"
#include "pqxx/transaction.hxx"
#include "pqxx/nontransaction.hxx"
#include "pqxx/compiler-public.hxx"
#include "pqxx/result.hxx"
#include "pqxx/prepared_statement.hxx"
#include "pqxx/transaction_base.hxx"
#include "pqxx/internal/statement_parameters.hxx"
...
int main(){
struct testData {
string uuid;
float rndNo;
string timestamp;
};
vector<testData> dataBuffer;
testData dbdata;
string queryStr;
const char* query;
stringstream connStream;
stringstream queryStream;
string DB_NAME = "dbname";
string DB_USER = "postgres";
string DB_PASSWORD = "password";
string DB_HOSTADDR = "127.0.0.1";
string DB_PORT = "1234";
string DB_SCHEMA = "test_schema";
string tableName = "test_table";
//Create Random data
for (int i = 0; i < 100000; i++) {
dbdata.uuid = "fe2b22ba-6ce7-4bbc-8226-d7696fe7a047";
dbdata.rndNo = i / 3.123;
dbdata.timestamp = systemDateTimeSQLFormat(0);
dataBuffer.push_back(dbdata);
}
stringstream connStream;
connStream << "dbname = " << DB_NAME << " user = " << DB_USER << " password = " << DB_PASSWORD << " hostaddr = " << DB_HOSTADDR << " port = " << DB_PORT;
connection dbConn(connStream.str());
if (dbConn.is_open()) {
cout << "Opened database successfully: " << dbConn.dbname() << endl;
}
else {
cout << "Can't open database" << endl;
return;
}
pqxx::nontransaction W(dbConn);
std::string m_insertCommand = "INSERT INTO test_schema.test_table (column1, column2, column3) VALUES";
int buffSize = dataBuffer.size();
for (size_t i = 0; i < buffSize; i++)
{
unsigned int countOf$ = i * 3;
for (unsigned int i = 0; i < 3; ++i)
{
if (i == 0)
{
m_insertCommand += "(";
}
else
{
m_insertCommand += ", ";
}
m_insertCommand += "$";
std::stringstream ss;
ss << countOf$ + i + 1;
m_insertCommand += ss.str();
}
if (i < buffSize - 1)
m_insertCommand += ") ,";
}
m_insertCommand += ")";
//FOLLOWING CODE NOT POSSIBLE WITH libpqxx v12
dbConn.prepare("insert_into_db", m_insertCommand);
pqxx::prepare::invocation = W.exec_prepared("insert_into_db"); //prepare doesn't have a member "invocation"
for (size_t i = 0; i < buffSize; i++)
{
inv(dataBuffer.at(i).rndNo)(dataBuffer.at(i).timestamp)(dataBuffer.at(i).uuid); //inv not defined
}
inv.exec();
return 1;
}
pqxx::prepare::make_dynamic_params will probably solve your problem. It's solved my problem. Use this way:
for (size_t i = 0; i < buffSize; ++i)
{
auto element = dataBuffer.at(i);
vector<string> vect;
vect.reserve(3);
vect.push_back(pqxx::to_string(element.rndNo));
vect.push_back(element.timestamp);
vect.push_back(element.uuid);
work.exec_params(m_insertCommand, pqxx::prepare::make_dynamic_params(vect));
}
From the version 7.6.0 dynamic_params are deprecated. params can be used instead. Here is the new solution:
for (size_t i = 0; i < buffSize; ++i)
{
auto element = dataBuffer.at(i);
pqxx::params;
params.reserve(4);
params.append(pqxx::to_string(element.rndNo));
params.append(element.timestamp);
params.append(element.uuid);
params.append(); // For example insert null variable
work.exec_params(m_insertCommand, params);
}

How do I change a pointer variable's value and keep the changes outside of a function without pass-by-reference?

I am doing a project for a class writing C-String-editing functions. 3/5 of the functions I have to write change the size of the char arrays I have to use, and they are being read through an ifstream input. Here is the program:
#include <iostream>
#include <fstream>
using namespace std;
void stringCopy(char *A, char *B);
bool stringCompare(char *A, char *B);
void stringConcatenation(char *A, char *B); //added const to make sure b is never changed
int stringPosition(char *A, char B);
int stringLength(char *A);
//-------------------MY-FUNCTIONS----------------------
int cStringLen(const char*); //finds string length, but doesn't account for null char
void reSize(char*&, int len, int newLen);
void input(char*& A, istream& is);
void printMessage(const char* word1, const char* word2, const char* message);
int main()
{
ifstream ifs{"input.txt"};
ofstream ofs{"output.txt"};
char* word1 = "";
char* word2 = "";
input(word1, ifs);
input(word2, ifs);
printMessage(word1, word2, "stringCopy()");
stringCopy(word1, word2);
printMessage(word1, word2, "after stringCopy()");
cout << endl;
input(word1, ifs);
input(word2, ifs);
printMessage(word1, word2, "stringCompare()");
if(stringCompare(word1, word2))
{
cout << "They match!" << endl;
}
else
{
cout << "They don't match!" << endl;
}
stringCopy(word1, word2);
printMessage(word1, word2, "comparing after stringCopy()");
if(stringCompare(word1, word2))
{
cout << "They match!" << endl;
}
else
{
cout << "They don't match!" << endl;
}
cout << endl;
input(word1, ifs);
input(word2, ifs);
printMessage(word1, word2, "stringConcatenation()");
stringConcatenation(word1, word2);
printMessage(word1, word2, "after stringConcatenation()");
cout << endl;
input(word1, ifs);
input(word2, ifs);
printMessage(word1, word2, "stringPosition()");
cout << "Searching for 'm' in word1..." << endl << "position returned is: " << stringPosition(word1, 'm') << endl;
cout << "Searching for 'n' in word2..." << endl << "position returned is: " << stringPosition(word2, 'n') << endl;
cout << endl;
input(word1, ifs);
cout << "stringLength()" << endl;
cout << "word1: " << word1 << endl;
cout << "The length of word1 is: " << stringLength(word1) << endl;
cout << "after stringLength()" << endl;
cout << "word1: " << word1 << endl;
return 0;
}
void stringCopy(char *A, char *B)
{
///GETTING THE SIZES OF BOTH ARRAYS
int counterA = cStringLen(A) + 1;
int counterB = cStringLen(B) + 1;
///MAKES SURE BOTH ARE THE SAME SIZE BEFORE COPYING
if(counterA < counterB)
{
reSize(A, counterA, counterB);
}
else
{
reSize(A, counterB, counterA);
}
///THE COPY
for(int i = 0; i < counterB; i++) *(A + i) = *(B + i); //each character is copied to A from B
}
bool stringCompare(char *A, char *B)
{
///getting length of one string
int counter = cStringLen(A);
///will move through string until diff char found
for(int i = 0; i < counter + 1; i++)
{
if(*(A + i) != *(B + i))
{
return false;
}
}
return true;
}
void stringConcatenation(char *A, char *B) //added const to make sure b is never changed
{
///getting length of both strings
int counterA = cStringLen(A)+1;
int counterB = cStringLen(B)+1;
///putting the length of both together for new string
const int COUNTERS = counterA + counterB - 1;
///making A the size of both strings - 1
reSize(A, counterA, COUNTERS);
///copying b to the parts of a past the original
for(int i = 0; i < counterB; i++)
{
*(A + (counterA - 1) + i) = *(B + i); //will override the '/0' char of A
}
}
int stringPosition(char *A, char B)
{
int counter = cStringLen(A) + 1;
///searching through string for char
for(int i = 0; i < counter; i++)
{
if(*(A + i) == B)
{
return i; //found!
}
}
///checking if b == '\0' and a '\0' isn't found somewhere before last spot of A
if(B == '\0')
{
return counter;
}
return -1; //not found
}
int stringLength(char *A)
{
int counter = cStringLen(A) + 1;
char* car = new char[counter + 1];
for(int i = 0; i < counter; i++)
{
*(car + 1 + i) = *(A + i);
}
*(car + 0) = counter;
delete[] A;
A = car;
/**
* Will take string as param.
* Shifts all characters to the right by one and store the length of the string in position 0.
- Length doesn't include position 0.
*/
return counter; //temp
}
//-----------------------------------------MY FUNCTIONS---------------------------------------------------------------------------
int cStringLen(const char* A) //finds string length, but doesn't account for null char
{
int counter = 0;
while(*(A + counter) != '\0')
{
counter++;
}
return counter;
}
void reSize(char*& A, int len, int newLen)
{
char* car = new char[newLen];
for(int i = 0; i < newLen; i++)
{
if(i < len)
{
*(car + i) = *(A + i);
}
else if(i >= len && i < newLen)
{
*(car + i) = '\0';
}
}
delete[] A;
A = car;
}
void input(char*& A, istream& is)
{
int wordSize = 0;
int arrSize = 1;
char c = 'o'; //checking char
char* car = new char[arrSize];
while((!(is.eof())) && (c != ' ' && c != '\t' && c != '\n'))
{
is.unsetf(ios_base::skipws);
is >> c;
if(is.eof())
{
delete[] A;
A = car;
return;
}
if(c != ' ' && c != '\t' && c != '\n')
{
if(wordSize == arrSize)
{
reSize(car, arrSize, arrSize * 2);
}
*(car + wordSize) = c;
}
wordSize++;
}
is.setf(ios_base::skipws);
delete[] A;
A = car;
}
void printMessage(const char* word1, const char* word2, const char* message)
{
cout << message << endl;
cout << "word1: " << word1 << endl << "word2: " << word2 << endl;
}
I thought I got it all done just fine. Keep in mind that I added the "&" operator after each of the pointer parameters already. Here is how they were before:
void stringCopy(char *&A, char *B);
bool stringCompare(char *A, char *B);
void stringConcatenation(char *&A, char *B); //added const to make sure b
is never changed
int stringPosition(char *A, char B);
int stringLength(char *&A);
But, when I got to class, my teacher said we weren't allowed to change the function headers in any way. So, I am stuck passing by value for the assignment. The problem is that I have no way of changing the c-strings outside the editing functions now. Any changes I do to them stay inside there.
It all compiles just fine, and, if I make the pointers pass-by-reference, the program runs flawlessly. I am just wondering how I could change the values of the c-strings outside of the editing functions. This assignment is starting to become a pain (so many f***ing restrictions).
I think what your teacher wants you to do is to change the value at the character pointer instead of creating a new string.
So instead trying to reassigning parameter A to a new char* you change the value that A points to in memory. That way the method that called your function still points to that same memory and when they access that location the get the value you changed from within your function.

C++ overloading == operator example

making chess game and i can't overload == operator (think that is problem, ofc if i added correctly elements in array).
enum squerState{EMPTY, ROOK, KNIGHT, BISHOP, QUEEN, KING, PAWN};
class Board
{
public:
Board();
~Board();
friend bool operator==(const Board& lhs, const Board& rhs);
squerState stanjePolja;
squerColor bojaPolja;
pieceColor bojaFigurice;
Board* board[8][8];
};
//.ccp
Board* piece;
for(int x= 0; x < 8; x++)
{
for(int y=0; y < 8; y++)
{
piece->stanjePolja = squerState::ROOK;
piece->bojaPolja = squerColor::WHITE;
piece->bojaFigurice = pieceColor::BLACK_PIECE;
board[y][x] = piece;
}
}
//overload ==
bool operator==(const Board& lhs, const Board& rhs)
{
return lhs.stanjePolja == rhs.stanjePolja;
}
//Draw test board
void Board::drawBoard()
{
for (auto y = 0; y < 8; y++)
{
for (auto x = 0; x < 8; x++)
{
if (board[y][x] == squerState::ROOK)
{
std::cout << 'O';
}
else
std::cout << 'X';
}
std::cout << std::endl;
}
}
Problem is when i try to draw test board with ROOK's.
if (board[y][x] == squerState::ROOK)
Thanks!
In the line
if (board[y][x] == squerState::ROOK)
it looks like the type of the expression on the left-hand side is Board*, but the type of expression on the right-hand side is enum squerState. You did not define an equals operator for those types and they can't be compared by other means.
You probably want your Board class to contain an array of SquareState instances.
enum Piece { None, Pawn, ... };
enum Color { Black, White };
struct SquareState
{
Piece piece_;
Color color_;
};
struct Board
{
void drawBoard() const;
SquareState board_[8][8];
};
void Board::drawBoard() const
{
for( int i = 0; i < 8; ++i )
{
for( int j = 0; j < 8; ++j )
{
switch( board_[ i ][ j ].piece_ )
{
case Piece::None:
std::cout << " ";
break;
case Piece::Pawn:
std::cout << "P";
break;
// ...
}
}
std::cout << std::endl;
}
}
I hope this helps.

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type