We are trying to convert this pseudocode into an actual code. The pseudo code is
Algorithm LinearFibonacci(k):
Input: A nonnegative integer k
Output: Pair of Fibonacci numbers (Fk,Fk−1)
if k ≤ 1 then
return (k,0)
else
(i, j)← LinearFibonacci(k−1)
return (i+ j, i)
I tried to translate it and came up with this
pair<int,int> LinearFibonnaci(int k) {
int i = 0;
int j = 0;
if (k <= 1) {
return make_pair(k, 0);
}
else {
make_pair(i, j) = LinearFibonnaci(k - 1);
return make_pair(i + j, i);
}
}
Am i doing this corretly because im not sure how to print out a pair function?
A std::pair object (not function) has two public members, first and second.
Since C++11, you can also extract an element from a pair using std::get.
See the following examples (testable here):
#include <iostream>
#include <utility>
#include <tuple>
std::pair<int, int> LinearFibonnaci(int k);
int main()
{
int k = 3;
// Explicitly declaring the type
std::pair<int, int> f = LinearFibonnaci(k);
// ^^^^^^^^^^^^^^^^^^^
std::cout << "F(" << k << ") = "
<< f.first << ", F(" << (k - 1) << ") = " << f.second << '\n';
// ^^^^^^^ ^^^^^^^^
k = 4;
// Since C++11: Using 'auto' let the compiler deduce the type
auto g = LinearFibonnaci(k);
// ^^^^
std::cout << "F(" << k << ") = "
<< g.first << ", F(" << (k - 1) << ") = " << g.second << '\n';
// ^^^^^^^ ^^^^^^^^
k = 5;
// Since C++17: Structured binding declaration
// See e.g. https://en.cppreference.com/w/cpp/language/structured_binding
auto [n, m] = LinearFibonnaci(k);
// ^^^^^^^^^^^
std::cout << "F(" << k << ") = " << n << ", F(" << (k - 1) << ") = " << m << '\n';
// ^^^ ^^^
k = 8;
// Since C++11: std::tie
// See e.g. https://en.cppreference.com/w/cpp/utility/tuple/tie
std::tie(n, m) = LinearFibonnaci(k);
// ^^^^^^^^^^^^^^
std::cout << "F(" << k << ") = " << n << ", F(" << (k - 1) << ") = " << m << '\n';
// ^^^ ^^^
k = 12;
// Since C++11: std::get
// https://en.cppreference.com/w/cpp/utility/pair/get
auto h = LinearFibonnaci(k);
std::cout << "F(" << k << ") = " << std::get<0>(h)
// ^^^^^^^^^^^^^^
<< ", F(" << (k - 1) << ") = " << std::get<1>(h) << '\n';
// ^^^^^^^^^^^^^^
}
std::pair<int, int> LinearFibonnaci(int k)
{
int i = 0;
int j = 0;
if (k <= 1) {
return {k, 0}; // You can use the constructor, here
}
else {
std::tie(i, j) = LinearFibonnaci(k - 1);
return {i + j, i};
}
}
As this question is marked C++17, structured bindings (auto[i,j]) can be used.
Another thing is that by using curly braces we can directly initialize the std::pair return object.
std::pair<int,int> LinearFibonnaci(int k) {
if (k <= 1)
{
return {k, 0};
}
else
{
auto[i, j] = LinearFibonnaci(k - 1);
return {i + j, i};
}
}
To get the result, again structured bindings can be used to retrieve the values:
auto[i, j] = LinearFibonnaci(x);
Related
I am implementing code for convolution in C++ (I know it exists already but I'm just doing it for practice since I'm a beginner), and while I can get the correct output, there are certain methods I'm trying that are giving unexpected output depending on how I access the values of the convolution that I store in an array and I'm not sure why.
The function code that works, whether I access the values by array indexing or with pointer incrementing, is:
void conv(int M, int* h, int L, int* x, int* y) {
int n, m = 0;
for (n = 0; n < L + M - 1; n++) {
for (m = std::max(0, n - L + 1); m <= std::min(n, M - 1); m++) {
*(y+n) += *(h + m) * *(x + n - m);
};
std::cout << "using array index: " << std::endl;
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
std::cout << std::endl;
std::cout << "using pointer: " << std::endl;
std::cout << "n = " << n << " " << "y = " << *(y+n) << " " << std::endl;
std::cout << std::endl;
//y++;
}
}
However, if I make slight changes to this (numbered below):
void conv(int M, int* h, int L, int* x, int* y) {
int n, m = 0;
for (n = 0; n < L + M - 1; n++) {
for (m = std::max(0, n - L + 1); m <= std::min(n, M - 1); m++) {
*y += *(h + m) * *(x + n - m); //[1]
};
std::cout << "using array index: " << std::endl;
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
std::cout << std::endl;
std::cout << "using pointer: " << std::endl;
std::cout << "n = " << n << " " << "y = " << *y << " " << std::endl; //[2]
std::cout << std::endl;
y++; //[3]
}
}
In this case, only accessing the values via pointer provides the correct output, while accessing it via array indexing provides random garbage.
My test code is:
int main()
{
const int M = 5; const int L = 6;
int y[M + L - 1] = {};
int x[L] = { 1, -2, 5, 3, 8, -4 };
int h[M] = { 1,2,3,4,5 };
int* yPtr = y; int* hPtr = h; int* xPtr = x;
conv(M, hPtr, L, xPtr, yPtr);
std::cout << "value after leaving conv" << std::endl;
for (int i = 0; i < M+L-1; i++) {
std::cout << "i = " << i << " " << "y = " << y[i] << std::endl;
}
}
which always provides the correct output even when accessing the array elements in the for loop of the conv provides the incorrect output.
For reference, the correct output is y = {1, 0, 4, 11, 26, 31, 53, 35, 24, -20}.
What am I doing wrong in the second example of conv to be getting the wrong values when using array indexing?
In the second version of the code, you are incrementing y as you go through the loop, so y[n] in the second version is equivalent to y[2*n] in the first. Once n reaches half the size of the array, y[n] is past the end of the array, thus garbage. *y is equivalent to y[0].
Your example is sufficiently weird to be a little difficult to read, but from your second version, this is fishy:
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
You're incrementing y as you go, so y[n] is going to go to weird places fast.
I saved Y as int * yOrig = y; and then used that, and I think I'm getting the output you expect, but I'm not sure.
I want to write a program that counts the number of times a certain vowel appears in a string but each value must be returned.
int vowel_count(string);
int main()
{
string str;
cout << "Enter a string";
cin >> str;
// Calling funtion:
vowel_count(str);
}
int vowel_count(string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for (int j = 0; j < var.length(); j++)
{
if (Var.at(j) == 'a')
sum_a++;
if (Var.at(j) == 'e')
sum_e++;
if (Var.at(j) == 'i')
sum_i++;
if (Var.at(j) == 'o')
sum_o++;
if (Var.at(j) == 'u')
sum_u++;
}
return sum_a;
return sum_e;
return sum_i;
return sum_o;
return sum_u;
}
Everytime I return , the program terminates, I would like to know how to I overrun the function of return.
You can use std::tuple to return multiple values from a function. Then you can either use std::get or std::tie to get at the values in the tuple. This avoids having to define a struct/class simply for the purpose of returning a result from your function vowel_count().
Since you tagged your question with C++14, I assume you haven't got C++17. However, with C++17 you can use structured bindings to extract the values instead.
For C++11/C++14:
#include<iostream>
#include<tuple>
using TupleVowel = std::tuple<int, int, int, int, int>;
TupleVowel vowel_count(std::string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for (int j = 0; j < var.length(); j++)
{
if (var.at(j) == 'a')
sum_a++;
if (var.at(j) == 'e')
sum_e++;
if (var.at(j) == 'i')
sum_i++;
if (var.at(j) == 'o')
sum_o++;
if (var.at(j) == 'u')
sum_u++;
}
return std::make_tuple(sum_a, sum_e, sum_i, sum_o, sum_u);
}
int main(void)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
std::tie(sum_a, sum_e, sum_i, sum_o, sum_u) = vowel_count("hello world");
std::cout << "sum_a = " << sum_a << ", sum_e = " << sum_e << ", sum_i = " << sum_i << ", sum_o = " << sum_o << ", sum_u = " << sum_u << std::endl;
}
Live demo.
You can also use std::get() with the index of the element like this without having to 'tie' the tuple elements to variables:
auto tup = vowel_count("hello world");
std::cout << "sum_a = " << std::get<0>(tup) << ", sum_e = " << std::get<1>(tup) << ", sum_i = " << std::get<2>(tup) << ", sum_o = " << std::get<3>(tup) << ", sum_u = " << std::get<4>(tup) << std::endl;
In C++17, you can just do:
auto [sum_a, sum_e, sum_i, sum_o, sum_u] = vowel_count("hello world");
Live demo.
When the type of the returned variable is the same, you can use a std::array (also std::vector or std::deque, but, given that the number of the returned variable is fixed, I suppose std::array is preferable)
I mean, something as follows
#include <array>
#include <iostream>
auto vowel_count (std::string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for ( auto const & ch : var )
if ( ch == 'a') ++sum_a;
else if ( ch == 'e') ++sum_e;
else if ( ch == 'i') ++sum_i;
else if ( ch == 'o') ++sum_o;
else if ( ch == 'u') ++sum_u;
return std::array<int, 5u>{ sum_a, sum_e, sum_i, sum_o, sum_u };
}
int main()
{
std::string str;
std::cout << "Enter a string";
std::cin >> str;
auto vc = vowel_count(str);
std::cout << "a: " << vc[0] << std::endl;
std::cout << "e: " << vc[1] << std::endl;
std::cout << "i: " << vc[2] << std::endl;
std::cout << "o: " << vc[3] << std::endl;
std::cout << "u: " << vc[4] << std::endl;
}
Observe that, starting from C++17, you can use structured bindings, exactly as suggested from jignatius in the std::tuple based solution.
auto [sum_a, sum_e, sum_i, sum_o, sum_u] = vowel_count(str);
std::cout << "a: " << sum_a << std::endl;
std::cout << "e: " << sum_e << std::endl;
std::cout << "i: " << sum_i << std::endl;
std::cout << "o: " << sum_o << std::endl;
std::cout << "u: " << sum_u << std::endl;
The answers above are way too complicated.
The easiest solution is a simple struct.
struct VowelResult {
int a;
int e;
int i;
int o;
int u;
};
VowelResult func () {
int sumA = 0;
int sumE = 0;
int sumI = 0;
int sumO = 0;
int sumU = 0;
//your code goes here...
return {sumA,sumE,sumI,sumO,sumU}; // order matters here
// alternatively:
// VowelResult res{};
// res.a = sumA;
// res.e = sumE;
// and so on...
// return res;
// alternatively alternativey you can simply use the struct directly to store the sums
}
I am trying to solve the Euler question 419
So far, I think I managed to build an algorithm to find the answer. Or at least it gives the correct result for first 40 step. But I need to compute 1,000,000,000,000th step. Solving first 40 step (with my algorithm) takes about 3-4 seconds. And bigger the iteration number increases, computation time increases as well. I don't think my computer can solve 1,000,000,000,000 iteration in a year.
What I do is simply using temporary vectors for both sequential number counting(form_1 and form_2) and keeping the calculated the result for each iteration(testVec). Here is my code below:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cmath>
std::vector<int> form_1;
std::vector<int> form_2;
std::vector<int> testVec;
void showVec(std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
std::cout << vec[i] << std::endl;
}
}
void resFin(int start, int stop, std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
if (i == 0)
{
//
form_1.push_back(vec[0]);
//std::cout << "form_1 pushed " << vec[0] << std::endl;
}
else
{
//
if (i != vec.size() - 1)
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
}
else
{
//
form_2.push_back(form_1.size());
form_2.push_back(vec[i - 1]);
form_1.clear();
form_1.push_back(vec[i]);
}
}
else
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_1.clear();
}
else
{
//
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_2.push_back(1);
//std::cout << "form_2 pushed " << 1 << std::endl;
form_2.push_back(vec[i]);
//std::cout << "form_2 pushed " << vec[i] << std::endl;
form_1.clear();
}
}
}
}
vec.clear();
for (unsigned long int k = 0; k < form_2.size(); k++)
{
//
vec.push_back(form_2[k]);
//std::cout << "vec pushed " << form_2[k] << std::endl;
}
//showVec(vec);
if (start + 1 != stop)
{
//
form_1.clear();
form_2.clear();
std::cout << "recursed to " << start + 1 << std::endl;
resFin(start + 1, stop, vec);
}
}
void stepFind(int stop, std::vector<int>& vec)
{
//
resFin(1, stop, vec);
}
void trimmVec(std::vector<int>& vec)
{
//
int a = 0;
int b = 0;
int c = 0;
for (unsigned long int i = 0; i < vec.size(); i ++)
{
//
switch (vec[i])
{
case 1:
a++;
a = a % 1073741824;
break;
case 2:
b++;
b = b % 1073741824;
break;
case 3:
c++;
c = c % 1073741824;
break;
default:
break;
}
}
std::cout << "a is " << a << "; b is " << b << "; c is " << c << std::endl;
}
int main()
{
//
testVec.push_back(1);
testVec.push_back(1);
stepFind(39, testVec);
//showVec(testVec);
trimmVec(testVec);
getchar();
return 0;
}
I think no one ought to wait more than a few hours to solve euler problems right? So I am doing something wrong here. So, are there such methods existed to minimize computing time, especially in vectors inside searching(I think this consumes the time most)?
It's allowed to leave template arguments blank (using <>), how would you leave a positional argument blank or rework this to achieve the same effect.
template <int i = 0, int j = 1, int k = 2>
void blah() {
std::cout << i << " " << j << " " << k << std::endl;
}
int main() {
blah(); // ok
blah<>(); // ok
blah<1>(); // ok, i = 1
blah<1,,3>(); // not ok, i = 1, j = 1 (default), k = 3
return 0;
}
It is not possible to do this. You have to pass it.
Here is a suggestion:
auto constexpr default_j = 1;
template <int i = 0, int j = default_j, int k = 2>
void blah() {
std::cout << i << " " << j << " " << k << std::endl;
}
int main() {
blah(); // ok
blah<>(); // ok
blah<1>(); // ok, i = 0
blah<1, default_j, 3>(); // ok, explicit and without duplicate magic numbers!
return 0;
}
Fun with macros (do not try this at home, kids):
#include <iostream>
template <int i = 0, int j = 1, int k = 2>
void blah() {
std::cout << i << " " << j << " " << k << std::endl;
}
#define _blah(D, V) (*#V ? V + 0 : D)
#define blah_3(I,J,K) blah<_blah(0,I), _blah(1,J), _blah(2,K)>()
#define blah_2(I,J) blah_3(I,J,)
#define blah_1(I) blah_3(I,,)
#define blah__(_1,_2,_3,X,...) blah ## X
#define blah(...) blah__(__VA_ARGS__,_3,_2,_1)(__VA_ARGS__)
int main() {
blah();
blah(, ,);
blah(1);
blah(1,,);
blah(1, ,3);
return 0;
}
typedef std::pair<int, bool> acq_pair; //edge, channel_quality
typedef std::pair<int, acq_pair> ac_pair;
typedef std::multimap<int, acq_pair> ac_map;
typedef ac_map::iterator It_acq;
int bits = acq_map.size();
std::cout << "bits = " << bits << std::endl;
std::vector<std::vector<bool> > c_flags (1 << bits);
for (i = 0; i < c_flags.size(); ++i)
{
for (j = 0; j < bits; ++j)
{
c_flags[i].push_back( (i & (1 << j)) > 0);
}
}
std::cout << "c_flags.size() = " << c_flags.size() << std::endl;
for(i = 0; i < c_flags.size(); ++i)
{
for(j = 0; j < bits; ++j)
{
std::cout << c_flags[i][j] << std::endl;
for(It_acq itc = acq_map.begin(); itc!= acq_map.end(); ++itc)
{
acq_pair it1 = itc->second;
itc->second.second = c_flags[i][j];
std::cout << itc->first << " : " << it1.first << " : " << it1.second << std::endl;
}
}
std::cout << "\n" << std::endl;
}
How can I access only one item from the multimap container at a time? I want to update only the jth value in the map, but when I iterate through the map all the bool values are changed. Is there a selective way to access the map container values?
The line itc->second.second = c_flags[i][j]; performed in a loop with itc from begin() to end() indeed performs assignment to every value of the map. If the goal was to modify only the j'th value in the map, there was no need for a loop over the entire map:
for(size_t j = 0; j < bits; ++j)
{
std::cout << c_flags[i][j] << std::endl;
It_acq itc = acq_map.begin(); // itc points at the beginning
advance(itc, j); // itc points at the j'th element
itc->second.second = c_flags[i][j]; // the assignment
for(It_acq itc = acq_map.begin(); itc!= acq_map.end(); ++itc)
{
acq_pair it1 = itc->second;
// itc->second.second = c_flags[i][j]; // no assignment here
std::cout << itc->first << " : " << it1.first << " : " << it1.second << std::endl;
}
}
If this map is used for indexed access in this manner, it may be worthwhile to consider switching to vector, though.