In this little program I try to order 3 numbers in a descending order. But seems like the line in which has "// 3 2 1 - doesn't work" as a comment isn't working as expected. It seems like my logic is correct.
My input:
4,
554 and
454545
Output: (which is not what I wanted)
554, 454545 and 4
If the value hold on the integer numbThree is bigger than numbOne and if numbOne is NOT bigger than numbTwo (NOT == else) it should ouput numbThree, numbTwo and numbOne in this order, why doesn't it work?
#include <iostream>
int main() {
int numbOne = 0, numbTwo = 0, numbThree = 0;
std::cin >> numbOne >> numbTwo >> numbThree;
if (numbOne > numbTwo) {
if (numbTwo > numbThree) {
std::cout << numbOne << " " << numbTwo << " " << numbThree << std::endl; // 1 2 3
}
else {
std::cout << numbOne << " " << numbThree << " " << numbTwo<< std::endl; // 1 3 2
}
}
else if (numbTwo > numbOne) {
if (numbOne > numbThree) {
std::cout << numbTwo << " " << numbOne << " " << numbThree << std::endl; // 2 1 3 - works
}
else {
std::cout << numbTwo << " " << numbThree << " " << numbOne << std::endl; // 2 3 1
}
}
else if (numbThree > numbOne) {
if (numbOne > numbTwo) {
std::cout << numbThree << " " << numbOne << " " << numbTwo << std::endl; // 3 1 2
}
else {
std::cout << numbThree << " " << numbTwo << " " << numbOne << std::endl; // 3 2 1 - doesn't work
}
}
std::cin.get();
std::cin.ignore();
return 0;
}
Thanks in advance for helping me out.
You cannot, in general, sort 3 numbers with 2 comparisons (see YSC's comment for a hard reason in terms of information content). Already your case 1 3 2 is flawed: what if numbThree > numbOne?
In general you have to allow for up to 3 comparisons. Of course, you can simply use the sort functionality provided by the standard library (i.e. by the language). If you don't want to (for some reason), then the correct logic (for ascending order) is
if(a<b)
if (b<c) // a,b,c // 2 comparisons
else if(a<c) // a,c,b // 3 comparisons
else // c,a,b // 3 comparisons
else
if( (a<c) // b,a,c // 2 comparisons
else if(b<c) // b,c,a // 3 comparisons
else // c,b,a // 3 comparisons
Thus, in 4 out of 6 possible cases we need 3 rather than 2 comparisons.
Not intended as an answer, but as an illustration of the comment by Sam Varshavchik:
What's wrong is that the code should use a small array, and std::sort,
instead of this kind of spaghetti code.
While Sam is right about production code, as an exercise of how to implement the logic, the question is okay and there is already a solution.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v(3);
if (! (std::cin >> v[0] >> v[1] >> v[2])) { exit(-1); }
std::sort(v.begin(), v.end(), std::greater<int>());
for (auto c: v) { std::cout << c << " "; }
std::cout << "\n";
}
Related
I need to insert for every element of vector it's opposite.
#include <iostream>
#include <vector>
int main() {
std::vector < int > vek {1,2,3};
std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
for (int i = 0; i < 3; i++) {
std::cout << i << " " << vek[i] << std::endl;
vek.insert(vek.begin() + i + 1, -vek[i]);
}
std::cout << std::endl;
for (int i: vek) std::cout << i << " ";
return 0;
}
OUTPUT:
1 2 3
0 1 // it should be 0 1 (because vek[0]=1)
1 -1 // it should be 1 2 (because vek[1]=2)
2 1 // it should be 2 3 (because vek[2]=3)
1 -1 1 -1 2 3 // it should be 1 -1 2 -2 3 -3
Could you explain me why function insert doesn't insert the correct value of vector? What is happening here?
Note: Auxiliary vectors (and other data types) are not allowed
During the for loop, you are modifying the vector:
After the first iteration which inserts -1, the vector becomes [1, -1, 2, 3]. Therefore, vec[1] becomes -1 rather than 2. The index of 2 becomes 2. And after inserting -2 into the vector, the index of the original value 3 becomes 4.
In the for loop condition, you need to add index i by 2, instead of 1:
#include <iostream>
#include <vector>
int main() {
std::vector < int > vek {1,2,3};
std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
for (int i = 0; i < 3 * 2; i+=2) {
std::cout << i << " " << vek[i] << std::endl;
vek.insert(vek.begin() + i + 1, -vek[i]);
}
std::cout << std::endl;
for (int i: vek) std::cout << i << " ";
return 0;
}
I am trying to split one large user given vector into x sub vectors. Everything "seems" to work as it should but the outcome is not right.
std::vector<std::vector<std::string>> split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
std::cout << "initial size: " << initial_vector.size() << std::endl;
int size_for_splitting = initial_vector.size();
std::cout << "split amount: " << thread_amount << std::endl;
int r = size_for_splitting / thread_amount;
std::cout << r << " need to be in each sub-vector" << std::endl;
std::cout << "There will be: " << size_for_splitting % thread_amount << " element remaining" << std::endl;
std::vector<std::vector<std::string>> perm_vector;
for (int x = 0; x < thread_amount; x++) {
std::vector<std::string> temp_vector;
for (int a = 0; a < r; a++) {
hm++;
std::cout << hm << std::endl;
temp_vector.push_back(initial_vector[hm]);
}
perm_vector.push_back(temp_vector);
}
std::cout << "Size of vector holding the sub vectors after splitting: " << perm_vector.size() << std::endl;
std::cout << perm_vector[0][0];
return perm_vector;
Running this code will give you this:
initial size: 7
split amount: 3
2 need to be in each sub-vector
There will be: 1 element remaining
1
2
3
4
5
6
Size of vector holding the sub vectors after splitting: 3
2
the vector i pass in is called test holds strings and is like so:
test.push_back("1");
test.push_back("2");
test.push_back("3");
test.push_back("4");
test.push_back("5");
test.push_back("6");
test.push_back("7");
Everything up until the last print statement seems to work. So perm_vector should hold 3 sub vectors containing every element in the main user given vector. When you print perm_vector[0][0] you would expect the output to be "1", but it is 2, also 7 should not be in the vector and 6 should be the last one but since it starts at 2, 7 is in it. the counter is defined outside of the function and it starts at 0. My question is why is it starting at 2?
I see two problems in your code:
hm is incremented before use. Furthermore, there is no point in making it global.
size_for_splitting is the result of an integer division, so the remainder is missing
I modified your code so the issues with hm are solved. I get the intended output <<1, 2>, <3, 4>, <5, 6>>, the 7 is missing as mentioned above.
#include <iostream>
#include<vector>
#include<string>
std::vector<std::vector<std::string> > split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
std::cout << "initial size: " << initial_vector.size() << std::endl;
int size_for_splitting = initial_vector.size();
std::cout << "split amount: " << thread_amount << std::endl;
int r = size_for_splitting / thread_amount;
std::cout << r << " need to be in each sub-vector" << std::endl;
std::cout << "There will be: " << size_for_splitting % thread_amount << " element remaining" << std::endl;
std::vector<std::vector<std::string> > perm_vector;
int hm = 0;
for (int x = 0; x < thread_amount; x++) {
std::vector<std::string> temp_vector;
for (int a = 0; a < r; a++) {
std::cout << hm << std::endl;
temp_vector.push_back(initial_vector[hm]);
hm++;
}
perm_vector.push_back(temp_vector);
}
std::cout << "Size of vector holding the sub vectors after splitting: " << perm_vector.size() << std::endl;
return perm_vector;
}
int main()
{
std::vector<std::string> test;
test.push_back("1");
test.push_back("2");
test.push_back("3");
test.push_back("4");
test.push_back("5");
test.push_back("6");
test.push_back("7");
std::vector<std::vector<std::string> > out = split_to_sub_vectors(test, 3);
}
Even if hm starts at 0, you increment it before you use it. Probably if you increment at the end of the internal for loop, you might get the output you expect. It's hard to tell the problem because I don't know what's in 'initial_vector', I assume initial_vector[0] = 1?
If you use the range-v3 library, implementing this logic becomes much easier, and less error prone:
#include <range/v3/all.hpp>
namespace rs = ranges;
namespace rv = ranges::views;
auto split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
auto res = initial_vector
| rv::chunk(thread_amount)
| rs::to<std::vector<std::vector<std::string>>>;
if (res.back().size() != thread_amount)
res.pop_back();
return res;
}
Here's a demo.
if x > INT_MAX or if x > INT_MIN the function will return 0... or that's what i'm trying to do :)
in my test case i pass in a value that is INT_MAX + 1... 2147483648 ... to introduce integer overflow to see how the program handles it.
i step through... my IDE debugger says that the value immediately goes to -2147483648 upon overflow and for some reason the program executes beyond both of these statements:
if (x > INT_MAX)
if (x < INT_MIN)
and keeps crashes at int revInt = std::stoi(strNum);
saying out of range
Must be something simple, but it's got me stumped. Why isn't the program returning before it ever gets to that std::stoi() given x > INT_MAX? Any help appreciated. Thanks! Full listing of function and test bed below: (sorry having trouble with the code insertion formatting..)
#include <iostream>
#include <algorithm>
#include <string> //using namespace std;
class Solution {
public: int reverse(int x)
{
// check special cases for int and set flags:
// is x > max int, need to return 0 now
if(x > INT_MAX)
return 0;
// is x < min int, need to return 0 now
if(x < INT_MIN)
return 0;
// is x < 0, need negative sign handled at end
// does x end with 0, need to not start new int with 0 if it's ploy numeric and the functions used handle that for us
// do conversion, reversal, output:
// convert int to string
std::string strNum = std::to_string(x);
// reverse string
std::reverse(strNum.begin(), strNum.end());
// convert reversed string to int
int revInt = std::stoi(strNum);
// multiply by -1 if x was negative
if (x < 0)
revInt = revInt * -1;
// output reversed integer
return revInt;
}
};
Main:
#include <iostream>
int main(int argc, const char * argv[]) {
// test cases
// instance Solution and call it's method
Solution sol;
int answer = sol.reverse(0); // 0
std::cout << "in " << 0 << ", out " << answer << "\n";
answer = sol.reverse(-1); // -1
std::cout << "in " << -1 << ", out " << answer << "\n";
answer = sol.reverse(10); // 1
std::cout << "in " << 10 << ", out " << answer << "\n";
answer = sol.reverse(12); // 21
std::cout << "in " << 12 << ", out " << answer << "\n";
answer = sol.reverse(100); // 1
std::cout << "in " << 100 << ", out " << answer << "\n";
answer = sol.reverse(123); // 321
std::cout << "in " << 123 << ", out " << answer << "\n";
answer = sol.reverse(-123); // -321
std::cout << "in " << -123 << ", out " << answer << "\n";
answer = sol.reverse(1024); // 4201
std::cout << "in " << 1024 << ", out " << answer << "\n";
answer = sol.reverse(-1024); // -4201
std::cout << "in " << -1024 << ", out " << answer << "\n";
answer = sol.reverse(2147483648); // 0
std::cout << "in " << 2147483648 << ", out " << answer << "\n";
answer = sol.reverse(-2147483648); // 0
std::cout << "in " << -2147483648 << ", out " << answer << "\n";
return 0;
}
Any test like (x > INT_MAX) with x being of type int will never evaluate to true, since the value of x cannot exceed INT_MAX.
Anyway, even if 2147483647 would be a valid range, its reverse 7463847412 is not.
So I think its better to let stoi "try" to convert the values and "catch" any out_of_range-exception`. The following code illustrates this approach:
int convert() {
const char* num = "12345678890123424542";
try {
int x = std::stoi(num);
return x;
} catch (std::out_of_range &e) {
cout << "invalid." << endl;
return 0;
}
}
Priority:
I am quite new at this obviously. I have tried reading other peoples errors for what I have and can't find a fix. When I take out the ofstream bit and switch fOut for cout then program works fine but I cant seem to get it to output to a file. I did make the file in advance.
Secondary:
I am suppose to also somehow use 1 loop for the range of x should be 0 to 10 in steps of 1, 10 to 50 in steps of 5( In the SquareMachine function). Same rule of 1 loop for the bit in main with 0 to 15 in 1 degree increments and 15 to 45 in 5 degree increments. I am sure there is a technique I am simply not seeing to combine my loops or perhaps a loop... hole.. hah get it? Anyway, primarily need assistance with the output file.
Thank you for any advice/assistance
Error(s):
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
week4.cpp: In function ‘int main()’:
week4.cpp:44: error: ‘struct std::ofstream’ has no member named ‘is’
week4.cpp: In function ‘int SquareMachine()’:
week4.cpp:92: error: ‘fOut’ was not declared in this scope
Code:
#include <cmath>
#include<stdlib.h>
#include <iostream>
#include t<ime.h>
#include<cstdlib>
#include<unistd.h>
#include<iomanip>
#include<fstream>
using namespace std;
//Global Variable(s)
long fact(long n);
// Prototype(s)
int SquareMachine();
// Program Header
void ShowProgramHeader()
{
fOut << "Name" << endl;
fOut << "Class and Date \n\n\n" << endl;
}
//Command Center
int main()
{
ofstream fOut( "sTable.out", ios::out| ios::trunc);
if( fOut.is.open())
{
ShowProgramHeader();
SquareMachine();
fOut << "Value---Output\n"<<endl;
for( long t =0; t <=15; t++)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
}
for( long t =20; t <=45; t=t+5)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
fOut.close();
}
}
else
cout<<"Unable to Open the file: sTable.out";
exit(-1);
}
long fact(long n)
{
if( n ==0 || n==1 )
return 1;
else if( n==2 || n <= 15)
return n * fact( n-1);
else if( n <=15 || n <=45)
return n * fact (n-5);
}
int SquareMachine()
{
double x = 10;
int n = 2;
double z;
fOut << "\nNumber Sqrt Exp Pow\n";
for ( z=0; z<=x; ++z)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
for ( z=15; z<=50; z= z+5)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
fOut << " \n End of Part 1\n"<< endl;
}
You have numerous errors in your code. Mostly optimization errors, also some typos. But always, you should listen to your compiler first, because it helps you find the problem. It is designed to do so!
Sometimes it literally says what you should do (or what not) in a case of error.
For example your compiler says:
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
It means that in that function's scope fOut cannot be seen. It is because it was declared in the main() function, so it is a local variable (only avaiable in a scope) and not global (avaiable from everywhere). If you want to use this variable in other functions too, it is a good practice to use references or pointers. (I would recommend you using global variables only if you really need to do so, in special cases)
Included headers: (don't include unnecessary headers)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath> // for Mathematical functions
Function prototypes:
void ShowProgramHeader(std::ofstream&);
long fact(long);
int SquareMachine(std::ofstream&);
Client code:
int main() {
std::ofstream f_out("sTable.txt", std::ios::out | std::ios::trunc);
if(f_out.is_open()) {
ShowProgramHeader(f_out);
SquareMachine(f_out);
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Output" << std::endl;
long i = 0; // for fact(long)
while(i <= 45) {
if(i <= 15 || i >= 20) {
f_out << std::left << std::setw(10) << i;
f_out << std::left << std::setw(10) << fact(i) << std::endl;
if(i <= 15) i++;
else i += 5;
} else i++;
}
f_out.close();
}
else {
std::cerr << "Unable to Open the file: sTable.out";
return -1;
}
return 0;
}
Function implementations from here!
Header (I'm not really sure what you are planning to do with this function):
void ShowProgramHeader(std::ofstream& f_out) { f_out << "Name\nClass and Date\n"; }
Square machine:
int SquareMachine(std::ofstream& f_out) {
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Square";
f_out << std::left << std::setw(20) << "Exp";
f_out << std::left << std::setw(10) << "Power" << std::endl;
float i = 0;
while (i <= 50) {
if(i <= 10 || i >= 15) {
f_out << std::left << std::setw(10) << std::setprecision(2) << i;
f_out << std::left << std::setw(10) << std::setprecision(3) << std::sqrt(i);
f_out << std::left << std::setw(20) << std::setprecision(10) << std::exp(i);
f_out << std::left << std::setw(10) << std::setprecision(4) << std::pow(i, 2) << std::endl;
if(i <= 10) i++;
else i += 5;
} else i++;
}
f_out << std::endl << "End of Part 1" << std::endl;
}
And finally the recursive factorial function! (You overcomplicated your solution, if you meant to use the factorial method). Also note that when your factorial's value becomes so big, you have to handle it. You should find a type that can store larger numbers than long!
long fact(long n) {
if(n <= 1) return 1;
return n * fact(n - 1);
}
Output (I used sTable.txt instead of sTable.out)
Name
Class and Date
Number Square Exp Power
0 0 1 0
1 1 2.718281746 1
2 1.41 7.389056206 4
3 1.73 20.08553696 9
4 2 54.59814835 16
5 2.24 148.4131622 25
6 2.45 403.4288025 36
7 2.65 1096.633179 49
8 2.83 2980.958008 64
9 3 8103.083984 81
10 3.16 22026.46484 100
15 3.87 3269017.25 225
20 4.47 485165184 400
25 5 7.200490291e+010 625
30 5.48 1.068647422e+013 900
35 5.92 1.586013445e+015 1225
40 6.32 2.353852703e+017 1600
45 6.71 3.493427058e+019 2025
50 7.07 5.184705458e+021 2500
End of Part 1
Number Output
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 1932053504 // long storage problem starts from here
14 1278945280 // wrong!
15 2004310016 // wrong!
20 -2102132736 // wrong!
25 2076180480 // wrong!
30 1409286144 // wrong!
35 0 // wrong!
40 0 // wrong!
45 0 // wrong!
Since long can contain a value up to ~2,1*10^9, however 13! ~ 6*10^9!
I want to print the first 2 values where the next is doubled from the current value.
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
bool doubled (int x, int y) { return x*2 == y; }
int main()
{
deque<int> di;
deque<int>::iterator diiter;
for (int i=0; i<=10; i+=2) di.insert(di.end(), i);
for (diiter = di.begin(); diiter != di.end(); ++diiter)
cout << *diiter << " ";
cout << endl;
diiter = adjacent_find(di.begin(), di.end(), doubled);
if (diiter != di.end()) {
cout << "found " << *diiter << " at " << distance(di.begin(), diiter)+1
<< " and " << *(++diiter) << " at " << distance(di.begin(), diiter)+1
<< endl;
}
}
the output is
0 2 4 6 8 10
found 4 at 3 and 4 at 2
not what I expected, which should be:
0 2 4 6 8 10
found 2 at 2 and 4 at 3
What's wrong with my code? I don't understand how the second position is decremented from the first one when I actually incremented it.
Thanks for all help.
Your program is giving strange results because it does not take in to account the fact, that order of evaluation of arguments to a function(In this case operator <<) is Unspecified.
My Answer here, explains the problem in detail & should be a good read.
You need to cout them on separate statements.
cout << "found " << *diiter;
cout << " at " << distance(di.begin(), diiter)+1;
cout << " and " << *(++diiter);
cout << " at " << distance(di.begin(), diiter)+1;
cout << endl;
This works well & outputs the correct/desired output.