Loop results in order - c++

I need your help with this problem. What I want to know is how to output of a loop based on the input.
Let's say we have a program that should measure if a triangle is right or not based on the inputs of the user. The input could be something like this:
6 8 10
25 52 60
5 12 13
Using the Pythagoras formula, we can determine if a triangle is or not right
C^2=a^2+b^2
Now, with the numbers provided, the output should be:
right
wrong
right
My question is..how can I do the calculation and check if it's right or not but format the output with the same order as the input?
This is what I've tried :
#include <iostream>
#include <cmath>
using namespace std;
int rightt;
int wrong;
int main()
{
double a = 0, b = 0, c = 0;
double formula = 0;
for (int i = 0; i < 1;)
{
cin >> a >> b >> c;
formula = pow(a, 2) + pow(b, 2);
if (formula == pow(c, 2) && formula != 0)
{
//cout << "Right";
rightt = rightt + 1;
}
if (formula != pow(c, 2) && formula != 0)
{
//cout << "Wrong";
wrong = wrong + 1;
}
if (a == 0 && b == 0 && c == 0)
{
i = 1;
cout << "\n";
while (rightt > 0)
{
cout << "\n" << "Right";
rightt = rightt - 1;
}
while (wrong > 0)
{
cout << "\n" << "Wrong";
wrong = wrong - 1;
}
}
}
system("pause");
}
But my output is not as I desired. The output is first set the right, and then the wrong ones. Thanks, and I hope you understand my problem.
EDIT:
I need to have the output after the 0 0 0 is reached and not before. So If I left the commented sections , the output will be Number-output-Number-output , and what I need is to allow users to enter all numbers and tell the software that he finishes when he enters 0 0 0 , and after that give the output based on the order.
Let's imagine this input :
6 8 10 >> this is right
25 52 60 >> This is wrong
5 12 13 >> This is right
0 0 0 >> This is the values used to end the inputs
Output should be
right
wrong
right

I think that rather than counting the number of right answers and wrong answers, you can STORE all of your answers IN ORDER, in an vector. Once you are done storing all your answers, you can just loop through the answers, and print them out one by one.
If you have not learned about vectors yet, the concept is simple... you have an array like collection of data. "push_back" always tacks the data to the end of the collection of data. So if your first answer was wrong, then right, then right, first you would push_back(wrong)...resulting in a collection of [wrong]. Then you would push_back(right) resulting in a collection of [wrong, right]. Again you would push_back(right) so your final vector would be a collection in the order of [wrong, right, right]
Now you just need to loop through your collection to print out the data. The "iter" is a pointer to each spot in your list. To get the "contents of each spot" you dereference, by saying (*iter) which will provide the string result values.
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
int main()
{
double a = 0, b = 0, c = 0;
double formula = 0;
int numberOfResults = 0;
int currentIndex = 0;
vector<string> answers;
for (int i = 0; i < 1;)
{
cout << "Enter the number of attempts: " << "\n";
cin >> numberOfResults;
string results[numberOfResults];
cout << "Enter a b and c" << "\n";
cin >> a >> b >> c;
formula = pow(a, 2) + pow(b, 2);
if (formula == pow(c, 2) && formula != 0)
{
results[currentIndex] = "Right";
answers.push_back("Right");
}
if (formula != pow(c, 2) && formula != 0)
{
results[currentIndex] = "Wrong";
answers.push_back("Wrong");
}
if (a == 0 && b == 0 && c == 0 || currentIndex == numberOfResults-1)
{
for (int j = 0; j < numberOfResults; j++){
cout << "\n" << results[j];
}
for(auto iter = answers.begin(); iter != answers.end(); ++iter){
cout << "\n" << (*iter);
}
return 0;
}
}
system("pause");
}

Related

what will be the value of (a*b*c )%k?

i have searched it everywhere, i only find the solution for (ab)%k which is ((a%k)(b%k))%k.
i want to write the code for it . suppose i have been given an array of numbers a1 ,a2 , a3 , a4 ... , an. i have to find whether product of numbers any subset from the array is divisible by k .
if(ai *aj .. *am %k == 0)
return true;
i want the code in c++.
i have tried the code :
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ll t;
cin >> t;
while(t--)
{
ll n , k ;
cin >> n >> k;
vector<ll>a;
ll product = 1;
int flag =0;
for(ll i =0 ; i < n ; i++)
{
int p;
cin >>p;
a.push_back(p);
if(p % k == 0)
{
flag = 1;
}
p = p%k; ................................(eqn 1)
product = product * p;
product = product %k; .................................(eqn 2)
}
if(flag == 1)
{
cout << "YES" << "\n";
continue;
}
product = product %k; ...............................(eqn 3)
if(product == 0)
{
cout << "YES" << "\n";
}
else
cout << "NO"<< "\n";
}
return 0;
}
This code passes all the test cases . if i remove the equation 1 from the code , it will pass all the testcases after it also .
but if i remove the equation 2 , the code gives it as wrong answer.
https://www.codechef.com/problems/DIVBYK
Can you tell me the concept behind it ?
The concept is that for a1,a2,b1,b2 satisfying:
a1 == b1 (mod k)
a2 == b2 (mod k)
it holds that
a1*a2 == b1*b2 (mod k)
In other words, the remainder of multiplying two numbers is the same as the remainder of multiplying just the remainders of the original numbers.
This is very handy because the latter does not suffer from overflow if k<sqrt(largest_representable_number).
One can prove by induction the same for product of N numbers.

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

I am trying to solve 12503 problem in UVA online judge. I think their is a problem while using string::back()

The problem is simple. But I tried to submit two different codes, one of them got a WA verdict while the other one got a AC verdict. The solutions are nearly same. Just by changing the input mechanism the solution gets accepted. I can't understand what the problem is. Link to the problem is here.
Abridged Problem Statement:
You have a robot standing on the origin of x axis. The robot will be given some instructions. Your
task is to predict its position after executing all the instructions.
LEFT: move one unit left (decrease p by 1, where p is the position
of the robot before moving)
RIGHT: move one unit right (increase p
by 1)
SAME AS i: perform the same action as in the i-th
instruction. It is guaranteed that i is a positive integer not
greater than the number of instructions before this
Input:
The first line contains the number of test cases T (T ≤ 100). Each test case begins with an integer n
(1 ≤ n ≤ 100), the number of instructions. Each of the following n lines contains an instruction.
Output
For each test case, print the final position of the robot.
Note that after processing each test case, the
robot should be reset to the origin.
Sample Input
2
3
LEFT
RIGHT
SAME AS 2
5
LEFT
SAME AS 1
SAME AS 2
SAME AS 1
SAME AS 4
Sample Output
1
-5
Here's the code which got AC verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
cin >> instruction;
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else { scanf("\n");
cin >> as >> in;
instructions[i] = instructions[in - 1];
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Here, is the code which got WA verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
getline(cin , instruction);
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else {
instructions[i] = instructions[instruction.back() - '0' - 1]; // I think the problem is here but don't know what it is.
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Maybe instruction.back() is creating some problem. Please clarify my doubt.

Possible infinite loop

I think my code has an infinite loop. Can someone tell me where I went wrong?
The code is supposed to find the number of valid numbers, with a valid number being a number without a digit repeating. For example, 1212 would be a non-valid number because 1 and 2 repeated.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a; int b; int count_validNums = 1; int digit; int last_digit; bool is_valid = true;
vector <int> num_list;
cout << "Enter numbers 0 < a <= b < = 10000: ";
cin >> a >> b;
// Checks for invalid input
if (a < 0 || b < 0 || a > 10000 || b > 10000) {
cout << "Invalid input";
return 1;
}
// Checks every number from the range [a,b]
for (int i = a; i <= b; i++){
last_digit = i % 10;
num_list.push_back(last_digit);
i = i / 10;
while (i != 0){
digit = i % 10;
if (find(num_list.begin(), num_list.end(), digit) != num_list.end()){
is_valid = false;
}
num_list.push_back(digit);
i = i / 10;
}
if (is_valid) count_validNums++;
}
cout << "They are " << count_validNums << " valid numbers between" << a << " and " << b << endl;
}
The inner while loop terminates when i == 0. Then the outer for loop increments it (so i == 1), then the inner loop reduces it to zero again. Then the other loop increments it, then ...
What is happening to cause the infinite loop is that you are constantly reducing the int i back down to 0. Consider these highlights:
`for(int i = a; i <= b; i++){
//stuff
while(i != 0){ //<--this forces i down to 0
//more stuff
i = i / 10;
}
//final stuff
}`
i here is all one variable, so any changes you make to it anywhere will affect it everywhere else it exists! Instead, you can try saying something like int temp = i; and then perform your operations on temp so that i remains independent, but because your for-loop terminates when i <= b and you are constantly resetting i to 0, it will never reach b.
Also, I noticed that in your check for valid numbers you verify that 0 < a,b < 10000, but later in your for-loop you seem to make the assumption that a <= b will be true. Unfortunately, your test does not ensure this, so the for-loop will immediately terminate for inputs where b < a is true (which your program currently allows) and your program will report answers that are likely incorrect. The same is true when I enter letters as input instead of numbers. You might want to revisit that portion of code.

Prevent loop from echoing if another same-value array element has been already echoed in C++

First of all, sorry for the mis-worded title. I couldn't imagine a better way to put it.
The problem I'm facing is as follows: In a part of my program, the program counts occurences of different a-zA-Z letters and then tells how many of each letters can be found in an array. The problem, however, is this:
If I have an array that consists of A;A;F;A;D or anything similar, the output will be this:
A - 3
A - 3
F - 1
A - 3
D - 1
But I am required to make it like this:
A - 3
F - 1
D - 1
I could solve the problem easily, however I can't use an additional array to check what values have been already echoed. I know why it happens, but I don't know a way to solve it without using an additional array.
This is the code snippet (the array simply consists of characters, not worthy of adding it to the snippet):
n is the size of array the user is asked to choose at the start of the program (not included in the snippet).
initburts is the current array member ID that is being compared against all other values.
burts is the counter that is being reset after the loop is done checking a letter and moves onto the next one.
do {
for (i = 0; i < n; i++) {
if (array[initburts] == array[i]) {
burts++;
}
}
cout << "\n\n" << array[initburts] << " - " << burts;
initburts++;
burts = 0;
if (initburts == n) {
isDone = true;
}
}
while (isDone == false);
Do your counting first, then loop over your counts printing the results.
std::map<decltype(array[0]), std::size_t> counts;
std::for_each(std::begin(array), std::end(array), [&counts](auto& item){ ++counts[item]; });
std::for_each(std::begin(counts), std::end(counts), [](auto& pair) { std::cout << "\n\n" << pair.first << " - " pair.second; });
for (i = 0; i < n; i++)
{
// first check if we printed this character already;
// this is the case if the same character occurred
// before the current one:
bool isNew = true;
for (j = 0; j < i; j++)
{
// you find out yourself, do you?
// do not forget to break the loop
// in case of having detected an equal value!
}
if(isNew)
{
// well, now we can count...
unsigned int count = 1;
for(int j = i + 1; j < n; ++j)
count += array[j] == array[i];
// appropriate output...
}
}
That would do the trick and retains the array as is, however is an O(n²) algorithm. More efficient (O(n*log(n))) is sorting the array in advance, then you can just iterate over the array once. Of course, original array sequence gets lost then:
std::sort(array, array + arrayLength);
auto start = array;
for(auto current = array + 1; current != array + arrayLength; ++current)
{
if(*current != *start)
{
auto char = *start;
auto count = current - start;
// output char and count appropriately
}
}
// now we yet lack the final character:
auto char = *start;
auto count = array + arrayLength - start;
// output char and count appropriately
Pointer arithmetic... Quite likely that your teacher gets suspicious if you just copy this code, but it should give you the necessary hints to make up your own variant (use indices instead of pointers...).
I would do it this way.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s;
vector<int> capCount(26, 0), smallCount(26, 0);
cout << "Enter the string\n";
cin >> s;
for(int i = 0; i < s.length(); ++i)
{
char c = s.at(i);
if(c >= 'A' && c <= 'Z')
++capCount[(int)c - 65];
if(c >= 'a' && c <= 'z')
++smallCount[(int)c - 97];
}
for(int i = 0; i < 26; ++i)
{
if(capCount[i] > 0)
cout << (char) (i + 65) << ": " << capCount[i] << endl;
if(smallCount[i] > 0)
cout << (char) (i + 97) << ": " << smallCount[i] << endl;
}
}
Note: I have differentiated lower and upper case characters.
Here's is the sample output:
output