I'm practicing C++ solving some exercises, but after the whole day, I couldn't solve on of them. Here's the exercise:
There are 100 hay and 100 cows divided into 3 groups.
-Group A: 1 cow needs 5 hay to be full
-Group B: 1 cow needs 3 hay to be full
-Group C: 3 cow needs 1 hay to be full
Calculate the number of cows in each group.
If all of them eat at the same time at the same speed then the code is not very hard.
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
for (a = 1; a <= 20; a++)
{
for (b = 1; b <= 32; b++)
{
c = 3 * (100 - 5 * c - 3 * c);
if ((a + b + c == 100))
cout << "Group A " << a << ", group B " << b << ", group c " << c << endl;
}
}
}
However since they eat at different speeds and some groups may start eating slower than others, some of them won't get full before the hay runs out. Input can be the time begin to eat of each group (BeginA, BeginB, BeginC) (Eg: 0mins, 10mins, 5mins) and the speed of each group (SpeedA, SpeedB, SpeedC) (measure in minutes per hay). And there are at least 2 groups are full. How can you find the numbers of cows in each group?
Edit: I have set up a test case:
BeginA=0, BeginB=10, BeginC=15
SpeedA=5, SpeedB=5, SpeedC=10
After 5 mins, x hay have been eaten.
10 mins, 2x hay have been eaten (100-2x hay).
15 mins, 2x + y hay have been eaten.
20 mins, 3x + 2y hay have been eaten.
Repeat until 2 groups are full
5x+3y+2/3z hay have been eaten
Then I stucked here: If x+y+z=100 and the hay have been eaten=100 then we have the answer.
Edit 2: Welp, still going nowhere, stuck in an infinite loop:
#include <iostream>
using namespace std;
int numCow(int a,int b,int c) {
int x=0, y=0, z=0;
for (x = 1; x < 100; x++)
{
for (y = 1; y < 100; y++)
{
for (z = 1; z < 100; z++)
if ((x + y + z == 100) && (a * x + b * y + c * z == 300))
cout << "Group A " << x << ", Group B " << y << ", Group C " << z << endl;
}
}
return 0;
}
int main()
{
int x, y, z, a=0, b=0, c=0, counter;
int Sx = 0, Sy = 0, Sz = 0, Bx, By, Bz;
x = 0; y = 0; z = 0;
counter = 0;
cout << "Begin time (s): ";
cin >> Bx >> By >> Bz;
cout << "Speed: ";
cin >> Sx >> Sy >> Sz;
Bx += Sx;
By += Sy;
Bz += Sz;
while (true) {
if (a!=15)
if (Bx == counter)
{
a++;
Bx += Sx;
}
if (b != 9)
if (By == counter)
{
b++;
By += Sy;
}
if (c!=3)
if (Bz == counter)
{
c++;
Bz += Sz;
}
if (a == 15 && b == 9) {
numCow(a, b, c);
break;
}
if (a == 15 && c == 3) {
numCow(a, b, c);
break;
}
if (c == 3 && b == 9) {
numCow(a, b, c);
break;
}
if (a == 15 && b == 9 && c == 3)
{
numCow(a, b, c);
break;
}
counter++;
}
}
Related
Link of Question : https://www.codechef.com/JULY20B/problems/PTMSSNG
Question Statement
Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Can anyone suggest where I'm going wrong or update my code or share a few test cases.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
vector<pair<ll, ll>> v;
ll n, m, a;
bool checkx = false;
cin >> n;
m = 4 * n - 1;
ll x[m], y[m];
ll c, d;
a = (m - 1) / 2;
for (ll i = 0; i < m; i++)
{
cin >> x[i] >> y[i];
v.push_back(make_pair(x[i], y[i]));
}
sort(v.begin(), v.end());
for (ll i = a; i >= 1; --i)
{
if (v[2 * i].first != v[2 * i - 1].first)
{
c = v[2 * i].first;
checkx = true;
if ((2 * i) % 4 == 0 && i >= 2)
{
if (v[2 * i].second == v[2 * i + 1].second)
{
d = v[2 * i + 2].second;
}
else
{
d = v[2 * i + 1].second;
}
}
else
{
if (v[2 * i].second != v[2 * i - 1].second)
{
d = v[2 * i - 1].second;
}
else
{
d = v[2 * i - 2].second;
}
}
break;
}
}
if (checkx)
{
cout << c << " " << d;
}
else
{
if (v[0].second == v[1].second)
{
d = v[2].second;
}
else
{
d = v[1].second;
}
cout << v[0].first << " " << d;
}
cout << endl;
}
return 0;
}
You don't need to do such complex things. Just input your x and y vectors and xor every element of each vector. The final value will be the required answer.
LOGIC :
(a,b)------------------(c,b)
| |
| |
| |
| |
(a,d)------------------(c,d)
See by this figure, each variable (a, b, c, d) occurs even number of times. This "even thing" will also be true for the N rectangles. Hence, you have to find the values of x and y which are occurring odd number of times.
To find the odd one out in such cases, the best trick is to xor every element of the vector. This works because of these properties of xor : k xor k = 0 and k xor 0 = k.
CODE:
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
signed main() {
std::size_t t, n;
std::cin >> t;
while (t--) {
std::cin >> n;
n = 4 * n - 1;
std::vector<int> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
std::cin >> x.at(i) >> y.at(i);
std::cout << std::accumulate(x.begin(), x.end(), 0L, std::bit_xor<int>()) << ' '
<< std::accumulate(y.begin(), y.end(), 0L, std::bit_xor<int>()) << '\n';
}
return 0;
}
here is a test case that your code doesn't work:
1
2
1 1
1 4
4 6
6 1
9 6
9 3
4 3
the output of your code is (6,3),but it should be (6,4).
I guess you can check more cases where the rectangles intersects.
from functools import reduce
for _ in range(int(input())):
n=int(input())
li=[]
li1=[]
for i in range(4*n-1):
m,n=map(int,input().split())
li.append(m)
li1.append(n)
r =reduce(lambda x, y: x ^ y,li)
print(r,end=' ')
r =reduce(lambda x, y: x ^ y,li1)
print(r,end=' ')
print()
Problem is :
Write a function that as an input argument receives a three-digit positive number and as a result has to get the sum between the largest and the smallest number obtained by the same 3 digits divided by the median digit.
Example: input argument to function 438
The largest with the same digits is 843, the smallest is 348, so it should be calculated (843 + 348) / 4.
I have tried it and got the result ok but my code seems to complicated so iam asking is there a better way to do it?
Thanks in advance
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int check(int x) {
int a, b, c, biggestNum, smallestNum, medianNum;
a = x / 100;
b = (x / 10) % 10;
c = x % 10;
if (a > b && a > c && b > c) {
biggestNum= a * 100 + b * 10 + c;
smallestNum= c * 100 + b * 10 + a;
medianNum= b;
}
else if (a > b && a > c && b < c) {
biggestNum= a * 100 + c * 10 + b;
smallestNum= b * 100 + c * 10 + a;
medianNum= c;
}
else if (b > a && b > c && a < c) {
biggestNum= b * 100 + c * 10 + a;
smallestNum= a * 100 + c * 10 + b;
medianNum= c;
}
else if (b > a && b > c && a > c) {
biggestNum= b * 100 + a * 10 + c;
smallestNum= c * 100 + a * 10 + b;
medianNum= a;
}
else if (c > a && c > b && a > b) {
biggestNum= c * 100 + a * 10 + b;
smallestNum= b * 100 + a * 10 + c;
medianNum= a;
}
else if (c > a && c > b && a < b) {
biggestNum= c * 100 + b * 10 + a;
smallestNum= a * 100 + b * 10 + c;
medianNum= b;
}
cout << "Smallest number is: " << smallestNum<< " ,biggest is: " << biggestNum << " and median is: " << medianNum<< "." << endl;
return (biggestNum + smallestNum) / medianNum;
}
int main() {
cout << "Enter one 3 digit positive number: ";
int x;
cin >> x;
float result = check(x);
cout << "The result is: " << result << "." << endl;
system("pause");
return 0;
}
The posted code can't really produce the right answer, considering that the result is calculated with integer arithmetic:
int check(int x) // <- note the type of the returned value
{
int biggestNum, smallestNum, medianNum;
// ...
return (biggestNum + smallestNum) / medianNum; // <- This is an integer division
}
int main()
{
int x;
// ...
float result = check(x); // Now it's too late to get the right result
}
The logic also doesn't consider all the possible cases, as a matter of fact it ignores duplicated digits and the big if else if construct, lacking a default branch (a final unconditioned else), leaves those uninitialized variables undetermined so that the following operation gives a meaningless result.
Given the assignment restrictions, I'd write something like the following
#include <utility>
// The assignment is about 3-digit numbers, you should check that x is actually in
// the range [100, 999]. Note that one of the extremes is a special case.
// Well, both, actually.
double I_ve_no_idea_how_to_name_this(int x)
{
constexpr int base = 10;
int smallest = x % base;
x /= base;
int median = x % base;
x /= base;
// Note that this "works" (extracting the third digit) even if
// x isn't a 3-digit number. If you can assure the input is well
// defined, you can simplify this.
int biggest = x % base;
// Now we can sort the previous variables.
using std::swap;
if ( median < smallest ) {
swap(median, smallest);
}
// Now I know that smallest <= median
if ( biggest < median ) {
swap(biggest, median);
}
// Now I know that median <= biggest
// ...
// Is that enough or am I missing something here?
// Please think about it before running the code and test it.
// Once the variables are sorted, the result is easily calculated
return (biggest + smallest + base * (2 * median + base * (biggest + smallest)))
/ static_cast<double>(median);
}
First, you should use more descriptive variable names and should initialize each variable on definition. These two steps help greatly in squashing bugs in complex programs. I know this one isn't complex, but it's a good habit to have. Second, the standard library can help with finding the largest and smallest digit, which then makes the rest simple. So here's an example without any if statements.
Finally, using namespace std; is a bad practice and should be avoided.
double check(int x)
{
int a = x / 100;
int b = (x / 10) % 10;
int c = x % 10;
int bigdigit = std::max({ a, b, c }); // find largest
int smalldigit = std::min({ a, b, c }); //find smallest
int middledigit = a + b + c - bigdigit - smalldigit; // sum of all digits minus largest and smallest gives the remaining one
int biggest = smalldigit + middledigit * 10 + bigdigit * 100;
int smallest = smalldigit * 100 + middledigit * 10 + bigdigit;
std::cout << "biggest: " << biggest << '\n';
std::cout << "smallest: " << smallest << '\n';
std::cout << "median: " << middledigit << '\n';
return (1.0 * biggest + 1.0 * smallest) / (1.0 * middledigit); --using double instead of int, as result could be fractional
}
try this...
int check(int x) {
int a,b,c,temp;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b*10)+(c*100) << "\n";
cout << "biggest: " << (a*100)+(b*10)+c << "\n";
cout << "median: " << b << "\n";
return (((a+c)*100)+(2*b*10)+(a+c))/b;
}
check this check function.
int check(int x) {
if(x >= 1000) x %= 1000; //or return -1;
//get digits
int M = x/100;
int C = (x/10)%10;
int m = x%10;
//unrolled bubble sort.
if(M < C) swap(M,C);
if(C < m) swap(C,m);
if(M < C) swap(M,C);
//simplified formula
return ((m+M)*(101))/C + 20;
}
//derivation of formula
B = M*100 + C*10 + m;
s = m*100 + C*10 + M;
B+s = (m+M)*100 + C*20 + (m+M)
= (m+M)*(100 + 1) + C*20
(B+s)/C = ((m+M)*(100 + 1) + C*20)/C
= ((m+M)*(101))/C + 20
The question need the user input two value, P and Q. The program then will output the number of right angle integer triangle as well as its perimeter from P to Q.
For example:
Input:
154 180
Output:
154 1
156 1
160 1
168 3
176 1
180 3
I think i need to find out the Pythagorean Triples in the P-Q range, but how to count the " number of right-angled triangle " ?
Here are my code :
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int P, Q, a, b, c, i = 0;
cin >> P >> Q;
for ( a = P; a <= Q; ++a)
{
for ( b = a; b <= Q; ++b)
{
for ( c = b; b <= Q; ++c)
{
if ((pow(a, 2) + pow(b, 2)) == pow(c, 2) && a + b + c <= Q)
{
i +=1;
cout << a + b + c << " " << i << endl;
}
}
}
}
return 0;
}
Super Thanks !!
We can count the right angle integer triangles with a specific perimeter by std::map which has the perimeters as keys and the number of triangles as values:
std::map<int, int> triangle_map;
Next, using the symmetry of triangles of exchanging a and b with flipping, we can restrict our finding search into the case of a<=b.
But if a==b then c=sqrt(2)*a which is not an integer when a is an integer.
Therefore the following double-loop search would well work for us and can find all the target triangles:
const int Qmax_a = (Q-1)/2; // 1 is the minimum value of c.
for (int a = 1; a <= Qmax_a; ++a)
{
const int a_sqr = a*a;
for (int b = a+1; b <= Q-a-1; ++b)
{
const int two_side_sqr = a_sqr + b*b;
// possible candidate
const int c = static_cast<int>(std::round(std::sqrt(two_side_sqr)));
const int perimeter = (a+b+c);
if((c*c == two_side_sqr) && (P <= perimeter) && (perimeter <= Q)){
triangle_map[perimeter] += 1;
}
}
}
Finally, we can get the desired output from the resulted map:
DEMO
for(const auto& p : triangle_map){
std::cout << p.first << "," << p.second << std::endl;
}
My first job as an intern was to write a program to compare certain characters in the filenames of two different directories, and if they match, rename them. I wrote a custom code to match the characters. The initial few files get renamed in both directories, but it breaks after a point, giving a vector subscript out of range error.
I have an idea of how to fix such a vector range error from all the other posts, but nothing seemed to work. Any input would be appreciated!
PS: I am not a coder and this is my third official program. I understand the code is a bit messy.
Here is the code:
#include<dirent.h>
#include<vector>
#include<sstream>
int main()
{
cout << "Comparer - Renamer v.0.1.beta\n\n";
string dr1, dr2;
int x, y;
DIR *d1;
struct dirent *dir1;
vector<string> a;
a.reserve(25000);
int i = 0;
cout << "Enter the first directory (format : log_2017...) : ";
cin >> dr1;
d1 = opendir(dr1.c_str());
if (d1){
while ((dir1 = readdir(d1)) != NULL){
i++;
a.push_back(dir1->d_name);
}
closedir(d1);
}
x = a.size();
cout << "\nEnter the second directory (format : 2017.12...) : ";
cin >> dr2;
DIR *d2;
struct dirent *dir2;
vector<string> b;
b.reserve(25000);
int j = 0;
d2 = opendir(dr2.c_str());
if (d2){
while ((dir2 = readdir(d2)) != NULL){
j++;
b.push_back(dir2->d_name);
}
closedir(d2);
}
y = b.size();
ostringstream osa, nsa, osb, nsb;
string oldname_a, newname_a, oldname_b, newname_b;
int u, v, w;
for (int l = 2; l < x; l++){
for (int k = l; k < y; k++){
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
if (a[l][4] == b[k][0] && a[l][5] == b[k][1] && a[l][6] == b[k][2] && a[l][7] == b[k][3] && a[l][9] == b[k][5] && a[l][10] == b[k][6] && a[l][12] == b[k][8] && a[l][13] == b[k][9]){
u = 0;
}
else{
u = 1;
}
if ((e - f) == 0 && abs(c - d) < 12){
v = 0;
}
else{
v = 1;
}
if ((e - f) == 1 && ((c == 58) || (c == 59) || (c == 0) || (c == 1) || (c == 2))){
w = 0;
}
else{
w = 1;
}
if (u == 0 && (v == 0 || w == 0)){
osa.str(string());
osa << dr1 << "\\" << a[l];
nsa.str(string());
nsa << dr1 << "\\" << l - 1 << ". " << a[l];
oldname_a = osa.str();
newname_a = nsa.str();
osb.str(string());
osb << dr2 << "\\" << b[k];
nsb.str(string());
nsb << dr2 << "\\" << l - 1 << ". " << b[k];
oldname_b = osb.str();
newname_b = nsb.str();
rename(oldname_a.c_str(), newname_a.c_str())
rename(oldname_b.c_str(), newname_b.c_str())
break;
}
}
}
return 0;
}
Presently the code is set such that it shows me how the comparison between the filenames is made.
It turns out I was not debugging properly, and the problem was in this part of the code:
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
I did not know that I couldn't assign an integer from a string/char directly to an int. I converted the char to int (which would give me the ASCII value of the char) and then subtracted it by 48 to convert it to decimal (I do not know if there is an easier way to do this, but this seemed to have worked for me!) The modified part looks like this:
c = ((int)a[l][20] - 48) * 10 + ((int)a[l][21] - 48);
d = ((int)b[k][14] - 48) * 10 + ((int)b[k][15] - 48);
e = ((int)a[l][17] - 48) * 10 + ((int)a[l][18] - 48):
f = ((int)b[k][11] - 48) * 10 + ((int)b[k][12] - 48);
There was also a small manual error in the conditions, which I also rectified.
When I try to start my C++ program it stops with error "5.exe has stopped working". This program supposed to calculate how many tiles you need for pool, if number of tiles on one side is non-round number, add one row of tiles to it. P.S. Sorry for my bad English.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,z;
int a,b;
cout << "Insert dimensions of pool in metres: " << endl;
cin >> x >> y >> z;
cout << "Insert dimensions of tile in centimeters: " << endl;
cin >> a >> b;
a=a/100;
b=b/100;
int brx = 0, brzx = 0, bry = 0, brzy = 0, bxpod = 0, bypod = 0;
if (x%a == 0) {
brx = x / a;
}
else {
brx = x / a + 1;
}
if (z%b == 0) {
brzx = z / b;
}
else {
brzx = z / b + 1;
}
if (y%a == 0) {
bry = y / a;
}
else {
bry = y / a + 1;
}
if (z%b == 0) {
brzy = z / b;
}
else {
brzy = z / b + 1;
}
if (x%a == 0) {
bxpod = x / a;
}
else {
bxpod = x / a + 1;
}
if (y%b == 0) {
bypod = y / b;
}
else {
bypod = y / b + 1;
}
int s = (brx*brzx + bry*brzy) * 2 + bxpod*bypod;
cout << "You need " << s << "tiles." << endl;
system("pause");
return 0;
}
Using a debugger, you can easily find that you have a division by 0 in the following lline:
if (x%a == 0) {
brx = x / a;
}
You are doing an integer division on "a":
a = a / 100;
So if a is lower than 100, a will be 0. 10 / 100 = 0.1 = 0 when cast as int.
You should use double instead of int