Member Avatar for TheFearful

Hey guys, I am having trouble in writing this code. I don't know where to start other than the beginning basic things. I just need to know how to start this thing because I know it is a loop, but loops are my weakest things as of right now. Here is the problem:

P2. (Bulls and Cows)
The number x is called happy if all its digits are different.
Examples: 2541 is a happy number and 2521 is not a happy number.
Let p and q are happy four-digit integers (p > 0, q > 0). Write a program that calculates two other numbers b (bulls) and c (cows) defined in the following way:

  • The number b takes the value of the number of pairs of equal digits from p and q with
    the same position.
  • The number c takes the value of the number of pairs of equal digits from p and q
    having different positions.
    Input data: p q
    Output: b c
    Examples:

    Input Output
    p = 1234, q = 5231 b = 2, c = 1
    p = 1234, q = 1234 b = 4, c = 0
    p = 4321, q = 5678 b = 0, c = 0
    p = 5612, q = 1265 b = 0, c = 4
    p = 3451, q = 2415 b = 1, c = 2

After that this is the other question:
To calculate an approximation of the value , a > 0, you can use the following iterative
formula:
xn+1 = 1/3(2xn + a/x^2n) , n >= 0
The approximation of a^1/3, is obtained through the sequence x0, x1, x2......xk starting with x0 = a.
The iteration should stop when the following condition is satisfied:

|(xk-xk-1)/xk| < epsilon for epsilon = 10^-5

or the number of the iteration is greater than 20.

Write a program that prints out the following table:

a            a^1/3                   pow(a, 1.0/3.0
---         --------                ----------------
0.5         ....                          ......
1.0             .....                     ........
1.5         .....                         .........
....        ......                       .........
9.0        .........                      .........
10.0    ...............                      ............

where:
- The numbers of the 2nd column are calculated using the iteration formula (1).
- The 3rdcolumn is the corresponding values of the function pow from cmath library.
Note: The numbers in the 2nd and 3rd columns should be printed out by using the manipulator setprecision (5).
Input data: No input data
Output: The table from the above

Here is what I have for this one so far:

int main()
{
double E, x, y, a, c;
a = 0.5;
x = a;
y= a;
E = pow ( 10.0, -5);
while (a < 20 && abs((x -y)/x) <= E)
{x = (1.0/3.0)*(2*x+a/(pow(x,2.0)));
c = pow(a, 1.0/3.0);
a += .5;
y = x;
cout << a << "  " << x << "  " << c << endl;}}

You're in over your head. Get a book and start reading. :)

Hi TheFearful,

Nothing to be afraid of here, except maybe frogboy's sarcasm. :)

In the first problem, since you don't actually need to perform any math on the input numbers, they don't need to be integers. You could play the same game, called "happy words" on 4-letter words: "HEAD" is a happy word, "FOOT" is not. Yes you need a loop, and iterating over the character positions in a string is much more obvious than extracting decimal digits from an integer. Does that help?

What is your question regarding the second problem? Actually, I know what the question is already, I can read minds: "why does my estimate suck?" The problem is you've collapsed the need for two loops into one. Simplify your logic by creating a function called estimateCubeRoot() which takes your "a" as an argument and returns your computed estimate of a^(1/3). That function needs a loop inside it which keeps revising the estimate until the difference between successive values is small enough. Then you still need a loop in your main() which provides successive values of a, and prints a, the estimated cube-root returned from your function, and the value computed by the pow() function.

Keep it simple, make functions that do simple logically-grouped things, call those functions when you need them to perform their tasks. This is the first part of "modular programming". In C++, the next part is to create groupings of functions and data into "classes". And related functions into separate files, and so on. :)

Dr. Azalov would disapprove of this. Although I also need help.

Hi inner circle, welcome to DaniWeb.

I don't know who Dr. Azalov is, your course instructor perhaps? What part would he disapprove of? Or did you mean the general "asking for help online" part? I'm not going to do your assignment for you, nor (with any luck) is anyone else on this forum. We're here to help you build and improve your programming skills, and lend some pointers and insight on more obscure aspects if we can.

If your course instructor has specifically said you should work out your assignments on your own, then it's up to you to do so. It's not my job to know who's in which class, and what their various restrictions might be. But since I'm still not going to hand over a completed working program, I don't believe it should be a problem.

Now if you need help, you should follow the same procedures as everyone else. Start writing your program, and get as far as you can on your own, then post your code here with specific questions on the parts you can't get working. And read "Read Me: Read This Before Posting A Question" (the clearly-marked sticky-post at the top of the forum).

Member Avatar for TheFearful

Hi TheFearful,

Nothing to be afraid of here, except maybe frogboy's sarcasm. :)

In the first problem, since you don't actually need to perform any math on the input numbers, they don't need to be integers. You could play the same game, called "happy words" on 4-letter words: "HEAD" is a happy word, "FOOT" is not. Yes you need a loop, and iterating over the character positions in a string is much more obvious than extracting decimal digits from an integer. Does that help?

What is your question regarding the second problem? Actually, I know what the question is already, I can read minds: "why does my estimate suck?" The problem is you've collapsed the need for two loops into one. Simplify your logic by creating a function called estimateCubeRoot() which takes your "a" as an argument and returns your computed estimate of a^(1/3). That function needs a loop inside it which keeps revising the estimate until the difference between successive values is small enough. Then you still need a loop in your main() which provides successive values of a, and prints a, the estimated cube-root returned from your function, and the value computed by the pow() function.

Keep it simple, make functions that do simple logically-grouped things, call those functions when you need them to perform their tasks. This is the first part of "modular programming". In C++, the next part is to create groupings of functions and data into "classes". And related functions into separate files, and so on. :)

Okay, I think I got the third one more correctly, but the second one, I don't know if I need to put any input values or anything like that. and would it be helpful if i used the for or while loop?

Yes, for P2 you need to input two values, P and Q. And since they're going to be 4-digit numbers (regardless of how you choose to represent them in your program), I think a for() loop is the more-readable way to program the solution.

int digit;
for (digit = 0; digit < 4; digit++) {
   ...
}
Member Avatar for TheFearful
#include <iostream>
 using namespace std;
int main()
 {
	 int r,q,digit,y,pw,qw,c,b,c1,b1;
	 c=0;b=0;
	 cout << "Enter two, four digit, strings of numbers" << endl;
	 cin >> r >> q;
	 pw = r;
	 qw = q;
	 for(digit=0;digit<4;digit++)
	 {
		 c1 = pw%10;
		 pw = pw/10;
		 for(y=0;y<4;y++)
		 {
			 b1 = qw %10;
			 qw = qw/10;
			 if (c1==b1)
			 {
				 if(digit==y)
					 b++;
				 else c++;
			 }
		 }
		 qw=q;
	 }
	 cout << "cows = " << c << endl;
	 cout << "bulls = " << b << endl;
	 return 0;
}

Okay, this is what I have, but I have no idea how to make it so that it will post an error when someone puts in a 4 digits with 2 of the same number or more. How am I able to do that?

For P2 its easy to come up with a O(n*m) \in O(n^2) solution, but can you come up with a linear time algorithm, possibly in O(n+m), where n is the length of the p and m is the length of q?

A readability point about your code so far:
You are allowed to use variables longer than 1 or 2 characters. From "The Tao of Programming" (a small comedic book, not immediately at hand, so I can't cite the author, and am quoting from memory), "Though your program be but three lines long, it will eventually need to be maintained." I would recommend variable names like p_digit, p_digit_val, p_remaining_val, (and same for q), bulls and cows.

As far as making sure the inputs are "happy numbers", think about what the statement requires. Can you think of a way to keep track of which digits you've seen so far? If you had a variable called times_digit_has_been_seen (though you can shorten it a bit), what type would make that variable? How would you give it a value (or values)? How would you check it later to determine whether the input number is ok?

While we're on the subject of error-checking user input (which is ALWAYS a good idea), what happens if the user enters a short number like 17? What happens if they enter a long number like 32768?

Doing great!

Member Avatar for TheFearful
#include <iostream>
using namespace std;
int main()
 {
	 int r, q, digit, y, pw, qw, c, b, c1, b1;
	 int num1, num2 ,num3, num4;
	 bool happy = true;
	 c = 0; b = 0;
	 cout << "Enter two, four digit, strings of numbers" << endl;
	 cin >> r >> q;
	 pw = r;
	 qw = q;

	 num4 = pw % 10;
	 if (num4 <= 0)
		 happy = false;
	 num3 = (pw / 10) % 10;
	 if (num3 <= 0)
		 happy = false;
	 num2 = (pw / 100) % 10;
	 if (num2 <= 0)
		 happy = false;
	 num1 = (pw / 1000) % 10;
	 if (num1 <= 0)
		 happy = false;
	 if (num1 == num2 || num1 == num3 || num1 == num4 || num2 == num3 || num2 == num4 || num3 == num4)
		 happy = false;

	 if (r > 999 && r < 10000 && happy == true)
	 {
		 for(digit = 0;digit < 4; digit++)
		 {
			 c1 = pw % 10;
			 pw = pw / 10;
			 for(y =  0; y < 4; y++)
			 {
				 b1 = qw % 10;
				 qw = qw / 10;
				 if (c1==b1)
				 {
					 if(digit==y)
						 b++;
					 else c++;
				 }
			 }
			 qw = q;
		 }
		 cout << "cows = " << c << endl;
		 cout << "bulls = " << b << endl;
	 }
	 else
		 cout << "not happy" << endl;
	 return 0;
}

I got this far. I have trouble on one last thing. I can't have any digit be 0 and it stays true for the first set of 4 digits, but I can't do the same for the second.

Your code tests only the first number for happiness. Consider putting your happy-determining code in a function called IsHappy(), which you can separately call for r and q (assigning the values to bool variables r_happy and q_happy, respectively).

You can't have any 0 digits because you specifically disallow them in your tests of num1 through num4. If you want to allow them, fix your comparisons so that 0 is a valid value. Also if you check ahead of time that q and r are >= 0, then you don't have to check whether each digit is negative. N % 10 will always be in the range [0,9] for non-negative N. For fun, just tested negative values of N. My C++ compiler (g++ for MinGW) gives -523 % 10 = -3, while ActivePython 2.6.4 gives -523 % 10 = 7. :)

Another thought on IsHappy(), while your code works fine (for r), the approach is brute-force, and becomes increasingly ugly for larger strings. What if you wanted to know if an 8-digit number is happy? What about text (say a "word") of near-arbitrary length? (Hint: have you learned about arrays yet?)

Member Avatar for TheFearful

i think i have it solved now. I do not know how to put this into a function yet, so I will keep it like this for now. There must not be a 0 in any of the digits, so I had to make sure that 0 could not be used. But you helped me so much and I finally solved this. Thank you (:

Awesome! Please mark your thread as "solved" for us. Happy coding!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.