String position multiply with array position [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Something wrong with my code, I want to multiply a string of numbers with an array of numbers(same length) and store the product in variable product, then I want to store this product of each column in my string variable (as a new values)
string var1 = "1232253759";
int arr[] = {5,3,7,1,2,8,9,2,2,1};
for(int i = 0; i < var1.size(); i++)
{
for(int n = 0; n < 10; n++)
{
int product = 0;
product = var1[i] * arr[n];
var1[i] = product;
}
}
there is a short output of this result:
245
-33
-231
25
50
400
-1008
32

So if im not mistaken this is what you want right.
where totalProduct will hold the product of every product and arr2 holds your columns. I added resultAsString so you have the result as string
note the var.at(i)-'0' which does the convertion you want or i think you are looking for.
for the conversion from int to string im using
std::stringstream ss;
ss << product;
a less C++ aproach would have been the atoi(product) function. or if using c++ 11 std:to_string(product)
Hope it helps
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string var1 = "1232253759";
int arr[] = {5,3,7,1,2,8,9,2,2,1};
int arr2[var1.size()];
int totalProduct = 0;
std::string resultAsString = "";
for(int i = 0; i < var1.size(); i++)
{
// for(int n = 0; n < 10; n++)
// {
int product = (var1.at(i)-'0') * arr[i];
// std::cout << product << "\n";
arr2[i] = product;
std::stringstream ss;
ss << product;
resultAsString += ss.str();
totalProduct += product;
//}
}
// for (int i = var1.size() - 1; i >= 0; i--)
// std::cout << arr2[i] << " ";
std::cout << resultAsString;
}

var1[i] is a char, not an int. char implicitly cast to int and calculation goes wrong. You need to map char with number to number itself ('1' -> 1, '2' -> 2). To do it subtract value of '0'. I.e. var1[i] - '0' it's number for char

Related

C++ - Reading table of numbers from file into 2D Array (only last row stored) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Starting with an input file that looks like this:
2 3
2 3 4
4 3 2
I am trying to read this data into a 2D array in C++ (the first row specifying number of rows / cols).
My code currently looks like:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open ("dataset.in");
// a matrix
int a_numrows;
int a_numcols;
int a[a_numrows][a_numcols];
fin >> a_numrows >> a_numcols;
cout << a_numrows << " " << a_numcols << endl;
for (int i = 0; i<a_numrows; i++)
{
for (int j = 0; j<a_numcols; j++)
{
fin >> a[i][j];
}
}
cout << a[0][0] << endl;
fin.close();
return 0;
}
However it seems as though in each row of the 2D array, the last row is being stored. Thus when a[0][0] is outputted, it returns 4. This behavior is not how I think things should work coming from other languages.
You must permute these lines:
int a[a_numrows][a_numcols];
fin >> a_numrows >> a_numcols;
to
fin >> a_numrows >> a_numcols;
int a[a_numrows][a_numcols];
I guess this is a mistake of inattention.
That's said, there are safer/better ways to declare/use 2D arrays. Here is a possible example:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream fin("dataset.in");
size_t n_rows, n_cols;
fin >> n_rows >> n_cols;
using T = int;
std::vector<T> array(n_rows * n_cols);
array.assign(std::istream_iterator<T>(fin), std::istream_iterator<T>());
fin.close();
//-----
for (size_t i = 0; i < n_rows; i++)
{
for (size_t j = 0; j < n_cols; j++)
{
std::cout << array[i * n_cols + j] << "\t";
}
std::cout << endl;
}
return 0;
}
Output:
g++ reader.cpp; ./a.out
2 3 4
4 3 2
Remember that when doing numerical computations it is generally better to store all the numbers into a contiguous memory chunk (like it is done in std::vector). In this situation it is easier for the compiler to vectorize your code.
To access components use:
[i*n_cols+j]: row-major (C-style) -> the given example,
more efficient to loop in this order: for i { for j ... } }
[j*n_rows+i]: column-major (Fortran-style) -> compatible with Blas & Lapack,
more efficient to loop in this order for j { for i ... } }
To declare an array in C++, the size has to be known at compile time. I.e. you can't pass a_numrows and a_numcols as array-dimensions as these are runtime values. For such an approach I would use a std::vector:
vector<vector<int>> a;
//... read a_numrows and a_numcols
a.resize(a_numrows); //resize creates #a_numrows empty columns
for(int i = 0; i < a_numrows; ++i)
{
for(int j = 0; j < a_numcols; ++j)
{
int value; fin >> value;
a[i].push_back(value); //access the ith row and add a new column with value inside
}
}

Storing multiple integers in a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:
for (int a = 0; a < 5; a++)
{
string ans;
int number;
int num;
number = rand() % 9 + 1;
cout << number << " ";
num = number;
to_string(num);
ans =+ num;
}
Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?
You can do something like this:
string ans;
int number;
for (int a = 0; a < 5; a++){
number = rand() % 9 + 1;
ans += to_string(number);
}
cout << ans;
to_string() returns a string.
You can simply try doing:
ans += to_string(num);
Or, better way to write your code for improved readability is to use a temporary string variable instead of an int num to store the number.
string temp;
string ans;
for (int a = 0; a < 5; a++)
{
//string ans;
int number;
//int num;
number = rand() % 9 + 1;
cout << number << " ";
//num = number;
temp = to_string(number);
ans += temp;
}
You do not want to declare your string ans inside the for loop because every time the loop runs, you ans will not hold the previous value anymore as it gets declared again.
There are a number of problems with your code.
you are declaring ans inside the loop, so it is created and destroyed on each loop iteration. If you want the loop to append 5 numbers to ans, you have to declare it outside of the loop instead.
std::to_string() outputs a new std::string as its return value. It does not "magically" turn the input value into a string type, like your code is assuming. You are not appending the returned string to ans at all.
=+ is not a valid append operator. It is interpreted as separate operators = and +. std::string does not have a = operator that takes an int as input, and does not have a unary + operator. You need to use the += operator instead.
Try this:
#include <string>
#include <iostream>
std::string ans;
for (int a = 0; a < 5; ++a)
{
int number = ...
...
ans += std::to_string(number);
}
// use ans as needed...
Alternatively, use std::ostringstream instead of std::to_string():
#include <string>
#include <sstream>
#include <iostream>
std::ostringstream oss;
for (int a = 0; a < 5; ++a)
{
int number = ...
...
oss << number;
}
std::string ans = oss.str();
// use ans as needed...
With that said, you are clearly using C++11 (when std::to_string() was introduced) or later, so you should be using a C++ random number generator instead of the one from C, eg:
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 9);
for (int a = 0; a < 5; ++a)
{
int number = dis(gen);
...
}

Fill a char array with int values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm using a library for an Arduino project that has a function I need to call. This function accepts just one parameter of type const char*. Let's call it foo.
I need to pass some int values to foo, so I convert them first using sprintf. So far so good.
The problem comes when I try to fill an array with int values converted to char and then call foo with each of the values in the array.
I hope this explains the problem better:
#include <iostream>
using namespace std;
// This function cannot be modified because
// is a part of a library
void foo(const char *bar){
cout << "Result: " << bar << endl;
}
int main() {
char *values[10]; // My array of values
char tmp[10]; // Temporary buffer for the int > char conversion
for(int i = 0; i < 10; i++){
int samplevalue = i * 2; // Just a sample value, not important
sprintf(tmp, "%d", samplevalue); // Copy the sample value to the temporary buffer
values[i] = tmp; // Assign the value of the temp var to a position in my values array
cout << values[i] << endl;
}
cout << "==============" << endl;
// Here comes the problem:
for(int i = 0; i < 10; i++){
foo(values[i]);
}
return 0;
}
The output of that code is the following:
0
2
4
6
8
10
12
14
16
18
==============
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
Result: 18
As you can see, all of the Result lines are equal to the last value assigned to the tmp var. I guess it's because each of the values in the values[10] array contains a pointer to the tmp variable instead of its actual value.
What I'd like to have is a different number on each Result line, as in the first for loop.
I guess it's pretty obvious that I'm not even near to be a C++ expert and any help will be highly appreciated.
Thanks!
A char * pointer and an array are not a string. Use std::string instead.
#include <iostream>
using namespace std;
// This function cannot be modified because
// is a part of a library
void foo(const char *bar)
{
cout << "Result: " << bar << endl;
}
int main(void)
{
std::string values[10]; // My array of values
char tmp[10]; // Temporary buffer for the int > char conversion
for (int i = 0; i < 10; i++) {
int samplevalue = i * 2; // Just a sample value, not important
sprintf(tmp, "%d", samplevalue); // Copy the sample value to the temporary buffer
values[i] = tmp; // Assign the value of the temp var to a position in my values array
cout << values[i] << endl;
}
cout << "==============" << endl;
// Here comes the problem:
for (int i = 0; i < 10; i++) {
foo(values[i].c_str());
}
return 0;
}
When using an array, all the pointers in your values array point to tmp, you can check that by looping through values and printing the address like this
fprintf(stdout, "%p\n", values[i]);
So because you sprintf() into tmp all the values, the value that will be printed is always the last one, there is no copy implied in
values[i] = tmp;
that just makes values[i] point to tmp, so when you access values[i] you really access tmp.
With std::string copy occurs.
Also, you should probably use a string stream to write numbers into each values[i] directly, because sprintf() is very dangerous.
Or even better use a real c++ solution like this one,
#include <iostream>
#include <vector>
#include <sstream>
// This function cannot be modified because
// is a part of a library
void foo(const char *bar)
{
std::cout << "Result: " << bar << std::endl;
}
int main(void)
{
std::vector<std::string> values;
for (int i = 0; i < 10; i++) {
values.push_back(std::to_string(2 * i));
std::cout << values[i] << std::endl;
}
std::cout << "==============" << std::endl;
for (size_t i = 0; i < values.size(); i++) {
foo(values[i].c_str());
}
return 0;
}
Note that now, you can change the number of elements in values and you can use it as an array if you need to, just read the documentation for std::vector.
Ok, I finally got to get it working. In Arduino strings are declared as String variable;, and the c_str() function converts a string into a const char *, so I convert the int number to String, and then to const char *:
for(int i = 0; i < 10; i++){
String tmp = String(i * 2);
values[i] = tmp.c_str();
}
And that's it! It works now :)

Project Euler task #8, code starts returning wrong answers after certain point [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having some sort of a problem in a task from
https://projecteuler.net/problem=8, (finding highest product of 13 consecutive numbers from a 1000-number string) where up to some point the program gives me predictable results and then the function returns a number very close to the unsigned long long int range. The point where it occurs depends on the values which were read, for instance if the string of numbers consisted mostly of 8s and 9s, it would happen sooner than it would if it had only 5s and 6s. Why does it happen?
#include <iostream>
#include <fstream>
using namespace std;
int product (int res, int a, char buffer[]){
for (int i = 0; i < a; i++){
//simple char to int conversion
res*=(buffer[i] - '0');
}
return res;
}
int main () {
char check;
int res = 1;
fstream plik;
plik.open ("8.txt");
unsigned long long int high;
unsigned long long int result;
//main function in the program
if (plik.good()){
char buffer [13];
for (int i = 0; i < 13; i++){
plik >> buffer[i];
}
result = product (res, 13, buffer);
high = result;
cout << high << endl;
//the main checking loop
while (!plik.eof()){
//just an interruption to make it possible to view consecutive products
//the iteration in the buffer
for (int i = 0; i < 12; i++){
buffer[i] = buffer[i+1];
}
plik >> buffer[12];
result = product (res, 13, buffer);
//comparison between the current product and highest one
if (high < result){
high = result;
}
cin >> check;
cout << high << endl;
//again a tool for checking where the problem arises
for (int i = 0; i < 13; i++){
cout << buffer[i] << " ";
}
cout << endl;
}
plik.close();
cout << high << endl;
}
return 0;
}
The program prints out the currently highest product and all the numbers currently contained in the array.
It looks like this:
The error
Use unsigned long long int instead of int to calculate the product. The product of 13 digits can easily become larger than the largest int.

How can I copy the values from a vector to an array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I get the dValues[] in the line double dValues[] = {what should i input here?}?Because I'm using an array. The goal is to get the mode.
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
double GetMode(double daArray[], int iSize) {
// Allocate an int array of the same size to hold the
// repetition count
int* ipRepetition = new int[iSize];
for (int i = 0; i < iSize; ++i) {
ipRepetition[i] = 0;
int j = 0;
bool bFound = false;
while ((j < i) && (daArray[i] != daArray[j])) {
if (daArray[i] != daArray[j]) {
++j;
}
}
++(ipRepetition[j]);
}
int iMaxRepeat = 0;
for (int i = 1; i < iSize; ++i) {
if (ipRepetition[i] > ipRepetition[iMaxRepeat]) {
iMaxRepeat = i;
}
}
delete [] ipRepetition;
return daArray[iMaxRepeat];
}
int main()
{
int count, minusElements;
float newcount, twocount;
cout << "Enter Elements:";
std::cin >> count;
std::vector<float> number(count);
cout << "Enter " << count << " number:\n";
for(int i=0; i< count ;i++)
{
std::cin >> number[i];
}
double dValues[] = {};
int iArraySize = count;
std::cout << "Mode = "
<< GetMode(dValues, iArraySize) << std::endl;
You already have all the values in your number vector, but if you wanted to copy those values into a new array called dValues, you have to allocate it on the heap (since you don't know the size at compile-time), copy the elements from the vector, and later free up that memory:
double *dValues = new double[number.size()];
for (size_t i = 0; i < number.size(); i++)
{
dValues[i] = number[i];
}
// whatever you need to do with dValues
delete [] dValues;
You're also not checking that you're within the bounds of your vector in the for loop. A safer implementation would use the push_back() method on the vector rather than assigning the values by index.
If I understood you correctly, you wish to copy the elements from the vector to array. If yes -
float *dValues = new float[count] ; // Need to delete[] when done
std::copy( number.begin(), number.end(), dValues );
std::copy is in algorithms header. But why do you want to use/create raw array for this task. You already have the vector number and just pass it to GetMode(..)