what is wrong with this code? I want to reverse a vector but my code is not working - vector

typedef vector list;
list reverse (const list& vect) {
list reversedList;
for (size_t i = vect.size()-1; i>=0; i--) {
reversedList.push_back(vect[i]);
}
return reversedList;
}

Related

Why does this doesnt work for transposing a matrix

For some reason the element b[m][n] is a random number instead of being 1. The same thing happens if I try to printf a[n][m]. Please I need some help on this!
#include <stdio.h>
#include <stdlib.h>
void **alloc(int n,int m)
{
int **x=(int**)malloc(n*sizeof(int*));
for(int i=1; i<=n; i++)
x[i] =(int*)malloc(m*sizeof(int*));
return x ;
}
void read(int **a,int n,int m,FILE *f)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
fscanf(f,"%d",&a[i][j]);
}
void print(int **a,int n,int m)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void transpose(int **a,int n,int m,int ***b)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
b[j][i]=a[i][j];
}
int main()
{
int n,m;
FILE *f;
f=fopen("in.txt","r");
if(f==NULL)
printf("Error");
fscanf(f,"%d %d",&n,&m);
int **a=alloc(n,m);
read(a,n,m,f);
int **b=alloc(m,n);
transpose(a,n,m,b);
print(b,m,n);
return 0;
}
This is the input and output, everything works except the b[m][n] element
There are several issues:
If this is C code, casting the result of malloc is at best pointless and at worst dangerous, as it might hide bugs. (This does not apply for C++ code.)
Your "inner" malloc uses sizeof(int*), when it should be using sizeof(int).
Your alloc function returns void**, which is not wrong as such, but why not let it return int** instead?
This is the most important one: C array indexing starts at zero, so if you have an array of N elements, they are numbered 0 though N-1.

How to split a string using a specific delimiter in Arduino?

I have a String variable and I want to extract the three substrings separeted by ; to three string variables.
String application_command = "{10,12; 4,5; 2}";
I cannot use substring method because this string can be like any of the following or similar patterns also.
String application_command = "{10,12,13,9,1; 4,5; 2}"
String application_command = "{7; 1,2,14; 1}"
The only thing that is common in these patterns is there are three sections separated by ;.
Any insight is much appreciated.
Thank you
I think you need a split-string-into-string-array function with a custom separator character.
There are already several sources on the web and at stackoverflow (e.g. Split String into String array).
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
You can use this function as follows (with ";" as separator):
String part01 = getValue(application_command,';',0);
String part02 = getValue(application_command,';',1);
String part03 = getValue(application_command,';',2);
EDIT: correct single quotes and add semicolons in the example.
The new SafeString Arduino library (available from the library manager) provides a number of tokenizing/substring methods without the heap fragmentation of the String class
See https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
for a detailed tutorial
In this case your can use
#include "SafeString.h"
void setup() {
Serial.begin(9600);
createSafeString(appCmd, 50); // large enought for the largest cmd
createSafeString(token1, 20);
createSafeString(token2, 20);
createSafeString(token3, 20);
appCmd = "{10,12,13,9,1; 4,5; 2}";
size_t nextIdx = 1; //step over leading {
nextIdx = appCmd.stoken(token1, nextIdx, ";}");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token2, nextIdx, ";}");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token3, nextIdx, ";}");
nextIdx++; //step over delimiter
// can trim tokens if needed e.g. token1.trim()
Serial.println(token1);
Serial.println(token2);
Serial.println(token3);
}
void loop() {
}
Also look at pfodParser which parses these types of messages { } for use by pfodApp.
Do not forget to call delete[] to free the memory after the use of the array, that said here is my solution:
String* split(String& v, char delimiter, int& length) {
length = 1;
bool found = false;
// Figure out how many itens the array should have
for (int i = 0; i < v.length(); i++) {
if (v[i] == delimiter) {
length++;
found = true;
}
}
// If the delimiter is found than create the array
// and split the String
if (found) {
// Create array
String* valores = new String[length];
// Split the string into array
int i = 0;
for (int itemIndex = 0; itemIndex < length; itemIndex++) {
for (; i < v.length(); i++) {
if (v[i] == delimiter) {
i++;
break;
}
valores[itemIndex] += v[i];
}
}
// Done, return the values
return valores;
}
// No delimiter found
return nullptr;
}
Here is an example of how to use:
void loop() {
String test = "1,2,3,4,5";
int qtde;
String* t = split(test, ',', qtde);
for (int i = 0; i < qtde; i++) {
Serial.println(t[i]);
delay(1000);
}
delete[] t;
}

QSignalSpy to capture a reference argument

It is not possible to capture an argument that has been passed as reference with a QSignalSpy:
QSignalSpy spy( myObject, SIGNAL(foo(int&)));
...
int& i=spy.at(0).at(0).value<int&>();
Since a QVariant can not contain a reference member. Plain logic.
But are there other solutions to check the passed-in argument?
Since Qt 5, we can simply connect to a lambda function, which makes the use of the QSignalSpy unnecessary:
std::vector<Value> values;
QObject::connect(myObject, &MyObject::foo,
[&](const auto &value)
{ values.emplace_back(value); });
myObject.somethingCausingFoo();
ASSERT_EQ(1u, values.size());
EXPECT_EQ(expectedValue, values.at(0));
An "ugly solution" would be to hack the fairly simple QSignalSpy code in order to handle the reference passed arguments. I provide a minimal working example for int reference arguments. The only changes were made to initArgs and appendArgs functions.
Notice that with this approach you will only be able to check the value of the passed argument by reference. You will not be able to change it's value.
In the initArgs function we check if we have references by argument and we populate the shouldreinterpret list.
void initArgs(const QMetaMethod &member)
{
QList<QByteArray> params = member.parameterTypes();
for (int i = 0; i < params.count(); ++i) {
int tp = QMetaType::type(params.at(i).constData());
if (tp == QMetaType::Void)
{
qWarning("Don't know how to handle '%s', use qRegisterMetaType to register it.",
params.at(i).constData());
// Check if we have a reference by removing the & from the parameter name
QString argString(params.at(i).constData());
argString.remove("&");
tp = QMetaType::type(argString.toStdString().c_str());
if (tp != QMetaType::Void)
shouldReinterpret << true;
}
else
shouldReinterpret << false;
args << tp;
}
}
and the appendArgs function, where we reinterpret the passed by reference arguments:
void appendArgs(void **a)
{
QList<QVariant> list;
for (int i = 0; i < args.count(); ++i) {
QMetaType::Type type = static_cast<QMetaType::Type>(args.at(i));
if (shouldReinterpret.at(i))
{
switch (type)
{
case QMetaType::Int:
list << QVariant(type, &(*reinterpret_cast<int*>(a[i + 1])));
break;
// Do the same for other types
}
}
else
list << QVariant(type, a[i + 1]);
}
append(list);
}
Complete code for reference:
class MySignalSpy: public QObject, public QList<QList<QVariant> >
{
public:
MySignalSpy(QObject *obj, const char *aSignal)
{
#ifdef Q_CC_BOR
const int memberOffset = QObject::staticMetaObject.methodCount();
#else
static const int memberOffset = QObject::staticMetaObject.methodCount();
#endif
Q_ASSERT(obj);
Q_ASSERT(aSignal);
if (((aSignal[0] - '0') & 0x03) != QSIGNAL_CODE) {
qWarning("QSignalSpy: Not a valid signal, use the SIGNAL macro");
return;
}
QByteArray ba = QMetaObject::normalizedSignature(aSignal + 1);
const QMetaObject *mo = obj->metaObject();
int sigIndex = mo->indexOfMethod(ba.constData());
if (sigIndex < 0) {
qWarning("QSignalSpy: No such signal: '%s'", ba.constData());
return;
}
if (!QMetaObject::connect(obj, sigIndex, this, memberOffset,
Qt::DirectConnection, 0)) {
qWarning("QSignalSpy: QMetaObject::connect returned false. Unable to connect.");
return;
}
sig = ba;
initArgs(mo->method(sigIndex));
}
inline bool isValid() const { return !sig.isEmpty(); }
inline QByteArray signal() const { return sig; }
int qt_metacall(QMetaObject::Call call, int methodId, void **a)
{
methodId = QObject::qt_metacall(call, methodId, a);
if (methodId < 0)
return methodId;
if (call == QMetaObject::InvokeMetaMethod) {
if (methodId == 0) {
appendArgs(a);
}
--methodId;
}
return methodId;
}
private:
void initArgs(const QMetaMethod &member)
{
QList<QByteArray> params = member.parameterTypes();
for (int i = 0; i < params.count(); ++i) {
int tp = QMetaType::type(params.at(i).constData());
if (tp == QMetaType::Void)
{
qWarning("Don't know how to handle '%s', use qRegisterMetaType to register it.",
params.at(i).constData());
QString argString(params.at(i).constData());
argString.remove("&");
tp = QMetaType::type(argString.toStdString().c_str());
if (tp != QMetaType::Void)
shouldReinterpret << true;
}
else
shouldReinterpret << false;
args << tp;
}
}
void appendArgs(void **a)
{
QList<QVariant> list;
for (int i = 0; i < args.count(); ++i) {
QMetaType::Type type = static_cast<QMetaType::Type>(args.at(i));
if (shouldReinterpret.at(i))
{
switch (type)
{
case QMetaType::Int:
int k = (*reinterpret_cast<int*>(a[i + 1]));
list << QVariant(type, &k);
break;
}
}
else
list << QVariant(type, a[i + 1]);
}
append(list);
}
// the full, normalized signal name
QByteArray sig;
// holds the QMetaType types for the argument list of the signal
QList<int> args;
// Holds the indexes of the arguments that
QList<bool> shouldReinterpret;
};

Infinite loop : Process not terminating properly

struct node
{
int data;
node* left;
node* right;
};
int secondlargest(struct node* a)
{
while(a->right != NULL){
secondlargest(a->right);
}
return a->data;
}
I am not able to trace where have I done the mistake and why its not coming out of the while loop.
Your mistake is that you shouldn't use an while but instead an if because it is recursive, but what do you want the function to return? the data of the last member? if so it should be like this:
int secondlargest(struct node* a) {
if(a == NULL) return -1;
secondlargestr(a);
}
int secondlargestr(struct node* a) {
if(a->right!=NULL) return secondlargest(a->right);
return (a->data);
}
If you insist on the recursive version, change the while to if.
int secondlargest(node* a)
{
if(a == null){
// if the first node is already NULL
return -1;
}
if(a->right == NULL){
return a->data;
}else{
return secondlargest(a->right);
}
}
Basics of recursion:
Must have base case
Break down problem size recursively
If you want the iterative way:
int secondlargest(node* a)
{
node* temp = a;
int data = -1;
while(temp != null){
data = temp->data;
temp = temp->right;
}
return data;
}

ArrayIndexOutOfBoundsException - why am I still having this problem?

I'm trying to print a chessboard to the console using a 2D array. For testing purposes, I'm trying to simply populate the board as 'x' chars. However, I keep getting an ArrayIndexOutOfBounds exception when I try to populate the array with the following:
public void setupBoard(){
for (int i=0; i < height; i++){
for (int j=0; j < width; j++){
boardArray[i][j] = 'x';
}
}
}
The error apparently occurs at boardArray[i][j] = 'x';
Everything seems to be in order, I dont see why this isnt working.
EDIT: I got the array to populate, but now I cannot format the printing correctly. The contents all print on one line, instead of as an 8x8 square of 'x' chars. Here's what I have now:
public void displayBoard(){
for (int k=0; k < boardArray.length; k++)
for (int l=0; l < boardArray[k].length; l++){
System.out.print(boardArray[k][l]);
}
System.out.println();
}
Well, presumably it's because you haven't created the board properly. Unfortunately you haven't shown us the array creation statement. It should be something like:
char[][] boardArray = new char[height][width];
EDIT: Okay, now for the printing part. Your current code is:
public void displayBoard(){
for (int k=0; k < boardArray.length; k++)
for (int l=0; l < boardArray[k].length; l++){
System.out.print(boardArray[k][l]);
}
System.out.println();
}
This is equivalent to:
public void displayBoard() {
for (int k = 0; k < boardArray.length; k++) {
for (int l = 0; l < boardArray[k].length; l++) {
System.out.print(boardArray[k][l]);
}
}
System.out.println();
}
... so you're only calling println after the outer loop has finished. If you just move the call to println to after the inner loop, it'll be fine:
public void displayBoard() {
for (int k = 0; k < boardArray.length; k++) {
for (int l = 0; l < boardArray[k].length; l++) {
System.out.print(boardArray[k][l]);
}
System.out.println();
}
}
Note that this sort of thing is clearer if you always include braces for loops, if statements etc.

Resources