C++ Fibonacci sequence - c++

The program I am trying to make is supposed to calculate and display each entry of the fibonacci sequence up to the 40th.
I believe I'm nearly there in terms of getting this done. The issue is: after the numbers 1 and 2, the sequence just seems to reset itself and leaves every subsequent number 1 place behind in the sequence.
This is the code:
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i==1)
{
cout << i << " " << b << endl;
}
else if (i==2)
{
cout << i << " " << b*2 << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}
I pre-programmed the first couple of numbers in the sequence because I couldn't get them to work properly, but after doing this, it seems to throw off the rest of the program.
The output from the code is this:
0 1
1 1
2 2
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144
13 233
14 377
15 610
16 987
17 1597
18 2584
19 4181
20 6765
21 10946
22 17711
23 28657
24 46368
25 75025
26 121393
27 196418
28 317811
29 514229
30 832040
31 1346269
32 2178309
33 3524578
34 5702887
35 9227465
36 14930352
37 24157817
38 39088169
39 63245986

It seems that I have solved this issue instantly after creating the post.
I decided to try pre-program the very first entry in the sequence (0) to be one, and completely remove the other pre-programmed parts in the sequence. This solved the entire thing.
Here's the working code:
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i == 0)
{
cout << i << " " << b << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}

You forgot to set a for the second case.
So when b = 2, c uses previous value of a which is 0.
Therefore, c = a+b = 0 + 2 = 2.
Set a = 1 in you second case:
else if (i==2)
{
a = 1 // This
cout << i << " " << b*2 << endl;
}

I pre-programmed the first couple of numbers in the sequence.. If you wish to go along this way, the following could be another method..
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
cout << 0 << " " << a << endl;//simply display the preprogrammed numbers
cout << 1 << " " << b << endl;
for (int i = 2; i < 40; ++i)//apply the formula for remaining elements
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
return 0;
}

Try the following changes in your program.
#include <iostream>
using namespace std;
int main() {
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i==0)
{
cout << i << " " << a << endl;
}
else if (i==1)
{
cout << i << " " << b << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}

Related

Color values always getting set to 204

I am trying to edit the pixels of an image with opencv.
I used this code:
#include<iostream>
#include<opencv2/opencv.hpp>
#include<stdint.h>
using namespace std;
uchar* array123()
{
uchar arr[3] = { 123, 123, 123 };
return arr;
};
int main()
{
cv::Mat img = cv::imread("img.jpg");
uchar* n;
for (int x = 0; x < img.cols; x++)
{
for (int y = 0; y < img.rows; y++)
{
n = array123();
cout << "n " << (int)*n << " " << (int)*(n + 1) << " " << (int)*(n + 2) << endl;
cv::Vec3b& color = img.at<cv::Vec3b>(y, x);
cout << "Before change " << (int)color[0] << " " << (int)color[1] << " " << (int)color[2] << endl;
color[0] = *n;
color[1] = *(n + 1);
color[2] = *(n + 2);
img.at<cv::Vec3b>(y, x) = color;
cv::Vec3b color2 = img.at<cv::Vec3b>(y, x);
cout << "After change " << (int)color2[0] << " " << (int)color2[1] << " " << (int)color2[2] << endl;
}
}
}
The console will log something like this:
n 123 123 123
Before change 153 123 26
After change 204 204 204
... repeating with After change always being 204 204 204 ...
And if I save the image is just a gray image with 204, 204, 204 RGB values
Does anyone know why this happens?

C++ Placing Random Values In A Multiplication Chart (Nested Loop)

I created a multiplication table for the integers 1...10. Here is the code:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
std::cout << "\t" << i * j;
}
std::cout << std::endl;
}
And my output is this:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The problem I am struggling with is that I need to insert a random number that represents an error value inside the multiplication table. For example:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 13 15 18 21 24 27 30
As you can see in this example, the error value is 13 where 3 x 4 = 12, but instead there is the number 13.
Should I use another loop to insert the random number? If so, how to go about it?
You can use <random> header file for this.
std::random_device rd;
std::mt19937 gen(rd());
// it produces uniformly distributed random integers in the range [a, b] (both inclusive)
std::uniform_int_distribution<> dis(0, 1); // either add 0 or 1 (1 will be the error -- can change a,b according to your need)
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
std::cout << "\t" << i * j + dis(gen); // just add the error value to your multiplication
}
std::cout << std::endl;
}
#include <iostream> // input/output
#include <random>
struct FieldData {
using Row = unsigned int;
using Col = unsigned int;
const Row rows{10};
const Col cols{10};
Row err_row;
Col err_col;
unsigned int err_value;
FieldData() {} // use default values for rows/cols
FieldData(Row max_row, Col max_col) : rows(std::move(max_row)), cols(std::move(max_col)) {} // use given values for rows/cols
};
void print_field(const FieldData& data)
{
for (FieldData::Row row=1;row <= data.rows; row++)
{
for (FieldData::Col col = 1; col <= data.cols; col++)
{
if (row == data.err_row && col == data.err_col)
std::cout << "\t" << data.err_value;
else
std::cout << "\t" << row*col;
}
std::cout << std::endl;
}
}
FieldData get_field(std::mt19937& generator)
{
FieldData data;
std::uniform_int_distribution<FieldData::Row> dist_rows(1, data.rows); // random for row
std::uniform_int_distribution<FieldData::Row> dist_cols(1, data.cols); // random for col
std::uniform_int_distribution<FieldData::Row> dist_result(1, data.rows*data.cols); // random for result
data.err_row = dist_rows(generator);
data.err_col = dist_cols(generator);
data.err_value = dist_result(generator);
if (data.err_value != data.err_row*data.err_col)
data.err_value--; // avoid correct value on error pos
return data;
}
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
while (true)
{
auto field = get_field(generator);
print_field(field);
// some code to ask the user and so on.... (std::cin ...)
std::cout << "Error value '" << field.err_value << "' is on row " << field.err_row << ", col " << field.err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
As requested by the questioner, a version without further constructs:
#include <iostream> // input/output
#include <random>
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
unsigned int rows = 10;
unsigned int cols = 10;
std::uniform_int_distribution<unsigned int> dist_rows(1, rows); // random for row (1 to value of field_rows)
std::uniform_int_distribution<unsigned int> dist_cols(1, cols); // random for col (1 to value of field_cols)
std::uniform_int_distribution<unsigned int> dist_result(1, rows * cols); // random for result
while (true) // infinite loop - must be interrupted explicitly with break or similar
{
unsigned int err_row = dist_rows(generator); // Generate the random number that defines the row
unsigned int err_col = dist_cols(generator); // Generate the random number that defines the col
unsigned int err_value = dist_result(generator); // Generate the random value
if (err_value != err_row * err_col)
err_value--; // avoid correct value on error position - simple decrement the value
// print_field
for (unsigned int row = 1; row <= rows; row++)
{
for (unsigned int col = 1; col <= cols; col++)
{
if (row == err_row && col == err_col) // condition to insert the error value
std::cout << "\t" << err_value;
else
std::cout << "\t" << row * col;
}
std::cout << std::endl;
}
//
// some code to ask the user and so on.... (std::cin ...)
//
std::cout << "Error value '" << err_value << "' is on row " << err_row << ", col " << err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
I hope this answer helps you, I have separated the different parts a little bit to make it more clearly arranged for you. The code should at least give you a rough idea how something like this could be implemented. Depending on the use case, a separate class or something similar would of course be appropriate.
The code in the second variant differs from the functionality only in that the uniform_int_distributions are outside the while(true) scope and thus are not always "rebuilt" as is the case in the first variant (since more dynamic and modularity would have been possible in principle).
Should I use another loop to insert the random number? If so, how to go about it?
You're only inserting one error, so it doesn't make much sense to a loop for that.
Well, why don't you first decide where the random number goes? Once you know that, you can modify the inner loop body, as follows:
int value = i * j;
if ((i == error_location.row) and (j = error_location.column)) {
value = // code for introducing an error, e.g. sample a random answer,
// or a random offset added to the correct answer etc.
}
std::cout << "\t" << i * j;
The decision of a position for the erroneous values can be made using the C++ header, as explained in this question. In your case it would be something like the following:
constexpr const int table_leg { 10 };
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> coordinate_distribution(0, table_leg - 1);
struct { int row, col; } error_location =
{ coordinate_distribution(gen), coordinate_distribution(gen) };
Notes:
I suggest replacing i with row or row_index and j with col or column or column_index; also, using the named constant instead of repeating the "magic number" 10.
I've assumed you don't want to store your multiplication table in a buffer, then replace one value in there with an error. If you are storing the table somewhere, you could avoid the complicated inner loop and just set the error after filling in all the correct values.
So thank's to everyone's input - especially #Wolfgang.
I did read up on C++11's random header file and it's functions.
I did create a source code with random functions and one without.
Any feed would be appreciated on how to make my source code more efficient.
Other than that, it achieves what I needed it to do.
#include <iostream>
#include <ctime>
#include <iomanip>
const unsigned int ROWS = 10;
const unsigned int COLUMNS = 10;
void randomValue(unsigned int &, unsigned int &, unsigned int &);
int main()
{
unsigned int rValue;
unsigned int cValue;
unsigned int pValue;
unsigned int rowError;
unsigned int columnError;
unsigned int productError;
unsigned int userRowGuess;
unsigned int userColumnGuess;
char choice;
do
{
randomValue(rValue, cValue, pValue);
std::cout << "\033[2J\033[0;0H"; // This code clears the screen
std::cout << std::endl << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::setw(35) << "+ Multiplication Table +" << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::endl << std::endl;
while (true)
{
rowError = rValue;
columnError = cValue;
productError = pValue;
if (productError == rowError * columnError)
{
productError--;
}
for (unsigned int row = 1; row <= ROWS; row++)
{
for (unsigned int column = 1; column <= COLUMNS; column++)
{
if (row == rowError && column == columnError)
{
std::cout << "\t" << "" << productError;
}
else
{
std::cout << "\t" << row * column;
}
}
std::cout << std::endl;
}
break;
}
std::cout << std::endl << std::endl;
std::cout << "\t\t" << "Type in the column number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userColumnGuess;
std::cout << std::endl;
std::cout << "\t\t" << "Type in the row number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userRowGuess;
std::cout << std::endl;
if (userRowGuess != rowError && userColumnGuess != columnError)
{
std::cout << "\t\t" << "Your answer was incorrect!" << std::endl << std::endl;
std::cout << "\t\t" << "Error value '" << productError << "' is located" << std::endl;
std::cout << "\t\t" << "on row " << rowError << ", column " << columnError << "." << std::endl;
}
else
{
std::cout << "\t\t" << "You are correct! You win!" << std::endl;
}
std::cout << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N'" << std::endl;
std::cout << "\t\t" << "for no & then press [Enter]: ";
std::cin >> choice;
while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N')
{
std::cout << std::endl;
std::cout << "\t\t" << "Invalid entry. Only 'Y' or 'N'" << std::endl;
std::cout << "\t\t" << "are accepted answers." << std::endl << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N' for" << std::endl;
std::cout << "\t\t" << "no & then press [Enter]: ";
std::cin >> choice;
}
std::cout << std::endl;
} while (choice == 'y' || choice == 'Y');
std::cout << "\t\t" << "Press [Enter] to continue....." << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
void randomValue(unsigned int &rValue, unsigned int &cValue, unsigned int &pValue)
{
srand((unsigned)time(NULL));
unsigned int r = rValue = (rand() % ROWS) + 1;
unsigned int c = cValue = (rand() % COLUMNS) + 1;
unsigned int p = pValue = (rand() % (ROWS * COLUMNS)) + 1;
}

Substring to divide text line by number of elements in the loop in C++ Producer Consumer pattern

I am writing the code which counts the lines in the document and split it into equal pats if the line more than 100. To split I am using string.substr(i, i+adding+ addCount). If i have to slit in three parts: First and third split part is OK, Second part has not only its part but also third part words in it. It looks something like this:
linesize: 331
divider3
0 Output I 110
1 EXPRESSION: Mrs. Bennet and her daughters then departed, and Elizabeth returned instantly to Jane, leaving her own and her
0 I
110I 110 0
was here OST
110 Output I 220
2 (error) EXPRESSION: relations’ behaviour to the remarks of the two ladies and Mr. Darcy; the latter of whom, however, could not be prevailed on to join in their censure of her, in spite of all Miss Bingley’s witticisms on fine eyes
110 I
220I 110 0
was here OST
220 Output I 416
3 EXPRESSION: be prevailed on to join in their censure of her, in spite of all Miss Bingley’s witticisms on fine eyes.
220 I
416I 110 86
was here OST
#include <iostream>
#include <deque>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <future>
#include <map>
#include <fstream>
#include <vector>
using namespace std;
atomic<bool> isReady{false};
mutex mtx;
condition_variable condvar;
map<string, int> mapper;
string line;
vector<string> block;
size_t line_index = 0;
int block_size = 100;
int limit_chars = 100;
int c = 0;
deque<vector<string>> dq;
void Producer() {
std::cout << " Producer " << std::endl;
fstream fl("/home/ostap/CLionProjects/WordsCount2/file.txt"); //full path to the file
if (!fl.is_open()) {
cout << "error reading from file" << endl;
}
else {
cout << "SUCCESS!!!" << endl;
while (getline(fl, line) && line_index < block_size) {
if (line.find_first_not_of(' ') != string::npos) { // Checks whether it is a non-space.
// There's a non-space.
cout<< "linesize: " << line.length() << endl;
if (line.length() / limit_chars > 1.4) {
int divider = (int) (line.length() / limit_chars);
int adding = (int) line.length()/divider;
//попробуй поміняти на while все через addCount
int addCount = 0;
int i = 0;
cout <<"divider" << divider<<endl;
while ( i < line.length()){
while (line[i + adding + addCount] != ' ') {addCount+=1;}
cout << i << " Output I " << i + adding + addCount << endl;
cout << "EXPRESSION: " << line.substr(i, i + adding + addCount) << endl; //to del
block.push_back(line.substr(i, i + adding + addCount));
cout << i << " I" << endl;
i = i + adding + addCount;
cout << i << "I" <<" " <<adding <<" "<< addCount <<endl;
++line_index;
addCount = 0;
cout << "was here OST" << endl;
}
}
else {
++line_index;;
block.push_back(line);
cout << "Line: " << line << endl;
}
if (line_index >= block_size) {
c++;
cout << c << endl;
{
lock_guard<mutex> guard(mtx);
//cout << "Producing message: " << x << " th" << endl;
dq.push_back(block);
}
line_index = 0;
block.clear();
}
condvar.notify_one();
}
cout << "Producer completed" << endl;
isReady = true;
// for (unsigned i = 0; i < block.size(); ++i) cout << ' ' << block[i];
// cout << '\n';
//this_thread::sleep_for(chrono::seconds(1));
}
}
}
void Consumer() {
while (true) {
unique_lock<mutex> lk(mtx);
if (!dq.empty()) {
vector<string> & i = dq.front();
dq.pop_front();
lk.unlock();
cout << "Consuming: " << i.data() << " th" << endl;
} else {
if(isReady){
break;
}
else {
condvar.wait(lk);
cout << "There are no messages remained from producer" << endl;
}
}
cout << "\nConsumer is done" << endl;
}
}
int main() {
//cout << "Hello, World!" << endl;
auto t1 = async(launch::async, Producer);
auto t2 = async(launch::async, Consumer);
//auto t3 = async(launch::async, Consumer);
t1.get();
t2.get();
//t3.get();
return -1;

C++ how to print out array values next to each other rather than underneath

I have made this section of code and would like it to print out like so:
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
Instead of being underneath of each other. Could any one point me in the correct direction?
#include <iostream>
int main(){
int n[10] = {1,2,3,4,5,6,7,8,9,10};
int x[10] = {0,0,0,0,0,0,0,0,0,0};
std::cout << "Element" <<std::endl;
for(int i = 0; i < 10; i++)
{
std::cout <<n[i] << std::endl;
}
std::cout << "Value" <<std::endl;
for(int y = 0; y <10; y++)
{
std::cout << x[y] << std::endl;
}
std::cout << "size of array: " << sizeof(n) << std::endl;
}
Print the values next to each other in one loop instead of using two loops (I changed the contents of x to make sure we see what's going on):
#include <iostream>
int main(){
int x[10] = {5,8,1,2,4,6,7,1,0,9};
std::cout << "Element Value" << std::endl;
for(int i = 0; i < 10; i++) {
std::cout << " " << i << " " << x[i] << std::endl;
}
std::cout << "size of array: " << sizeof(x) << std::endl;
return 0;
}
https://ideone.com/vAaLyl
Output:
Element Value
0 5
1 8
2 1
3 2
4 4
5 6
6 7
7 1
8 0
9 9
size of array: 40
Other than that, there's no need for the array n; use your index as the index.

C++: Using MPI's gatherv to concatenate vectors of differing lengths

so I'm trying to copy over vectors of different lengths between MPI processes in C++, namely taking vectors on all of the nodes and concatenating them into a new vector on node 0.
I have the following code, which does not return what I expected, driving me crazy, and causing trouble further down the line.
The code is this (abbreviated):
//previously summed all of numfrags to make _numFrag
//numfrags is a vector of the local sizes of _fragLoc
//_numFrag is the total of numfrags
MPI::COMM_WORLD.Barrier();
cout << _myid << "local numFrag = " << _fragLoc.size() << endl;
MPI::COMM_WORLD.Barrier();
for (unsigned i = 0; i < _fragLoc.size(); ++i) cout << "fragloc(" << i << ") = " << _fragLoc[i] << endl;
MPI::COMM_WORLD.Barrier();
vector<int> outVector (_numFrag);
int displ[_numprocs];
if (_myid == 0) {
double sum = 0;
for (int i = 0; i < _numprocs; ++i) {
displ[i] = sum;
cout << _myid << " : " << i << " : " << sum << endl;
sum += numfrags[i];
}
}
MPI::COMM_WORLD.Barrier(); MPI::COMM_WORLD.Gatherv(&_fragLoc[0], numfrags[_myid], MPI::INT, &outVector[0], &numfrags[0], &displ[0], MPI::INT,0);
MPI::COMM_WORLD.Barrier();
if (_myid == 0) {
cout << "X numFrag = " << _numFrag << endl;
for (unsigned i = 0; i < _numFrag; ++i) cout << "outVector(" << i << ") = " << outVector[i] << endl;
}
Giving a simple example, I have a four-node run. Here are the variable inputs as pseudocode:
int _numprocs = 4;
vector<int> numfrags = {0,1,0,1};
vector<int> _fragLoc <node 0> = {};
vector<int> _fragLoc <node 1> = {12};
vector<int> _fragLoc <node 2> = {};
vector<int> _fragLoc <node 3> = {37};
int _numFrag = 2;
The output is:
2local numFrag = 0
3local numFrag = 1
0local numFrag = 0
1local numFrag = 1
fragloc(0) = 12
fragloc(0) = 37
0 : 0 : 0
0 : 1 : 0
0 : 2 : 1
0 : 3 : 1
0: after stage 2
X numFrag = 2
outVector(0) = 0
outVector(1) = 0
But I expected the individual fragLoc's to be put together into outVector and this isn't happening. Any advice? I'll clean up the barriers when I'm done debugging.
As far as I can tell, the code above works as expected.
#include <iostream>
#include <mpi.h>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
MPI::Init(argc, argv);
int _myid = MPI::COMM_WORLD.Get_rank();
int _numprocs = MPI::COMM_WORLD.Get_size();
vector<int> _fragLoc;
switch(_myid) {
case 0: break;
case 1: _fragLoc.push_back(12); break;
case 2: break;
case 3: _fragLoc.push_back(37); break;
}
int locNumFrag = _fragLoc.size();
cout << _myid << "local numFrag = " << locNumFrag << endl;
MPI::COMM_WORLD.Barrier(); // for printing
vector<int> numfrags(_numprocs);
MPI::COMM_WORLD.Allgather(&locNumFrag, 1, MPI::INT, &numfrags[0], 1, MPI::INT);
int _numFrag = 0;
for (int i=0; i<_numprocs; i++)
_numFrag += numfrags[i];
for (unsigned i = 0; i < _fragLoc.size(); ++i)
cout << "fragloc(" << i << ") = " << _fragLoc[i] << endl;
MPI::COMM_WORLD.Barrier(); // for printing
vector<int> outVector (_numFrag);
int displ[_numprocs];
if (_myid == 0) {
double sum = 0;
for (int i = 0; i < _numprocs; ++i) {
displ[i] = sum;
cout << _myid << " : " << i << " : " << sum << endl;
sum += numfrags[i];
}
}
MPI::COMM_WORLD.Gatherv(&_fragLoc[0], numfrags[_myid], MPI::INT, &outVector[0], &numfrags[0], &displ[0], MPI::INT,0);
if (_myid == 0) {
cout << "X numFrag = " << _numFrag << endl;
for (unsigned i = 0; i < _numFrag; ++i) cout << "outVector(" << i << ") = " << outVector[i] << endl;
}
MPI::Finalize();
return 0;
}
Running gives
$ mpirun -np 4 ./gatherv
0local numFrag = 0
1local numFrag = 1
fragloc(0) = 12
2local numFrag = 0
3local numFrag = 1
fragloc(0) = 37
0 : 0 : 0
0 : 1 : 0
0 : 2 : 1
0 : 3 : 1
X numFrag = 2
outVector(0) = 12
outVector(1) = 37