## Cs 60 Solved Assignment 2011 Nfl

In the programs that we have examined to this point, each of the statements is executed once, in the order given. Most programs are more complicated because the sequence of statements and the number of times each is executed can vary. We use the term *control flow* to refer to statement sequencing in a program.

*median*(the third largest one).

*Solution*: is the same as .

The while loop condition uses instead of so it is an assignment statement (which makes always and the body of the loop will never be executed). It's better to style to avoid using .

boolean done = false; while (done = false) { ... }

boolean done = false; while (!done) { ... }

The variable should be defined outside the loop. By defining it inside the loop, a new variable is initialized to 0 each time through the loop; also it is not even accessible outside the loop.

for (int i = 1; i <= N; i++) { int sum = 0; sum = sum + i; } System.out.println(sum);

Category Wind Speed (mph) 1 74 - 95 2 96 - 110 3 111 - 130 4 131 - 155 5 155 and above

double x = -32.2; boolean isPositive = (x > 0); if (isPositive = true) System.out.println(x + " is positive"); else System.out.println(x + " is not positive");

*Solution*: It uses the assignment operator instead of the equality operator . A better solution is to write .

int i = 0, n = 20; for (i = 0; i < n; i--) System.out.print("x");

*Solution*: Replace the i < n condition with -i < n. Replace the i-- with n--. ( In C, there is a third: replace the < with a +.)

if (x > 0); System.out.println("positive");

*Solution*: always prints regardless of the value of because of the extra semicolon after the statement.

**RGB to HSB converter.**Write a program that takes an RGB color (three integers between 0 and 255) and transforms it to an HSB color (three different integers between 0 and 255). Write a program that applies the inverse transformation.

**Boys and girls.**A couple beginning a family decides to keep having children until they have at least one of either sex. Estimate the average number of children they will have via simulation. Also estimate the most common outcome (record the frequency counts for 2, 3, and 4 children, and also for 5 and above). Assume that the probability p of having a boy or girl is 1/2.

public static void main(String[] args) { int N = Integer.parseInt(args[0]); int x = 1; while (N >= 1) { System.out.println(x); x = 2 * x; N = N / 2; } }

*Solution*: Prints all of the powers of 2 less than or equal to n.

**Boys and girls.**Repeat the previous question, but assume the couple keeps having children until they have another child which is of the same sex as the first child. How does your answer change if p is different from 1/2?

*Surprisingly, the average number of children is 2 if p = 0 or 1, and 3 for all other values of p. But the most likely value is 2 for all values of p.*

c = 0; while (b > 0) { if (b % 2 == 1) c = c + a; b = b / 2; a = a + a; }

*Solution*: a * b.

12 midnight 1am 2am ... 12 noon 1pm ... 11pm

public class Test { public static void main(String[] args) { if (10 > 5); else; { System.out.println("Here"); }; } }

*Solution*: 39/121.

**Number-to-English.**Write a program to read in a command line integer between -999,999,999 and 999,999,999 and print the English equivalent. Here is an exhaustive list of words that your program should use: negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, hundred, thousand, million . Don't use hundred, when you can use thousand, e.g., use one thousand five hundred instead of fifteen hundred. Reference.

**Gymnastics judging.**A gymnast's score is determined by a panel of 6 judges who each decide a score between 0.0 and 10.0. The final score is determined by discarding the high and low scores, and averaging the remaining 4. Write a program that takes 6 real command line inputs representing the 6 scores and prints their average, after throwing out the high and low scores.

**Quarterback rating.**To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) as follows:

- Completion ratio: W = 250/3 * ((A / B) - 0.3).
- Yards per pass: X = 25/6 * ((C / B) - 3).
- Touchdown ratio: Y = 1000/3 * (D / B)
- Interception ratio: Z = 1250/3 * (0.095 - (E / B))

*quarterback rating*is computed by summing up the above four quantities, but rounding up or down each value so that it is at least 0 and and at most 475/12. Write a program that takes five command line inputs A, B, C, D, and E, and prints the quarterback rating. Use your program to compute Steve Young's 1994 record-setting season (112.8) in which he completed 324 of 461 passes for 3,969 yards, and threw 35 touchdowns and 10 interceptions. As of 2014, the all-time single-season record is 122.5 by Aaron Rodgers in 2011.

**Decimal expansion of rational numbers.**Given two integers p and q, the decimal expansion of p/q has an infinitely repeating cycle. For example, 1/33 = 0.03030303.... We use the notation 0.(03) to denote that 03 repeats indefinitely. As another example, 8639/70000 = 0.1234(142857). Write a program that reads in two command line integers p and q and prints the decimal expansion of p/q using the above notation.

*Hint*: use Floyd's rule.

**Friday the 13th.**What is the maximum number of consecutive days in which no Friday the 13th occurs?

*Hint*: The Gregorian calendar repeats itself every 400 years (146097 days) so you only need to worry about a 400 year interval.

*Solution*: 426 (e.g., from 8/13/1999 to 10/13/2000).

**January 1.**Is January 1 more likely to fall on a Saturday or Sunday? Write a program to determine the number of times each occurs in a 400 year interval.

*Solution:* Sunday (58 times) is more likely than Saturday (56 times).

for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (i != j) System.out.println(i + ", " + j); for (int i = 0; i < N; i++) for (int j = 0; (i != j) && (j < N); j++) System.out.println(i + ", " + j);

int cnt = 0; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int k = 0; k < 10; k++) if (2*i + j >= 3*k) cnt++; System.out.println(cnt);

^{2}is equal to (1

^{3}+ 2

^{3}+ ... + n

^{3}).

*Solution*: Always print .

**Sample standard deviation of uniform distribution.**Modify Exercise 8 so that it prints the sample standard deviation in addition to the average.

**Sample standard deviation of normal distribution.**that takes an integer N as a command-line argument and uses Web Exercise 1 from Section 1.2 to print N standard normal random variables, and their average value, and sample standard deviation.

**Loaded dice.**[Stephen Rudich] Suppose you have three, three sided dice. A: {2, 6, 7}, B: { 1, 5, 9}, and C: {3, 4, 8}. Two players roll a die and the one with the highest value wins. Which die would you choose?

*Solution*: A beats B with probability 5/9, B beats C with probability 5/9 and C beats A with probability 5/9. Be sure to choose second!

**Thue–Morse sequence.**Write a program ThueMorse.java that reads in a command line integer n and prints the Thue–Morse sequence of order n. The first few strings are 0, 01, 0110, 01101001. Each successive string is obtained by flipping all of the bits of the previous string and concatenating the result to the end of the previous string. The sequence has many amazing properties. For example, it is a binary sequence that is

*cube-free*: it does not contain 000, 111, 010101, or where is any string. It is

*self-similar*: if you delete every other bit, you get another Thue–Morse sequence. It arises in diverse areas of mathematics as well as chess, graphic design, weaving patterns, and music composition.

int digits = 0; do { digits++; n = n / 10; } while (n > 0);

*Solution*: The number of bits in the binary representation of a natural number n. We use a loop so that code output 1 if n = 0.

*Hint*: they will form a triangle if and only if the sum of every two values is larger than the third.

*Hint*: the three lengths will form an obtuse triangle if and only if (i) the sum of every two values is larger than the third and (ii) the sum of the squares of every two side lengths is greater than or equal to the square of the third.

Answer.

int M = 987654321; String s = ""; while (M != 0) { int digit = M % 10; s = s + digit; M = M / 10; }

int i = 10; i = i++; i = ++i; i = i++ + ++i;

Moral: don't write code like this.

**Formatted ISBN number.**Write a program ISBN2.java that reads in a 9 digit integer from a command-line argument, computes the check digit, and prints the fully formatted ISBN number, e.g, 0-201-31452-5.

**UPC codes.**The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a product. The least significant digit d

_{1}(rightmost one) is a check digit which is the uniquely determined by making the following expression a multiple of 10:

(d_{1}+ d_{3}+ d_{5}+ d_{7}+ d_{9}+ d_{11}) + 3 (d_{2}+ d_{4}+ d_{6}+ d_{8}+ d_{10}+ d_{12})

As an example, the check digit corresponding to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since

(8 + 0 + 0 + 0 + 5 + 4) + 3 (2 + 1 + 0 + 0 + 8 + 0) = 50

and 50 is a multiple of 10. Write a program that reads in a 11 digit integer from a command line parameter, computes the check digit, and prints the the full UPC. *Hint*: use a variable of type to store the 11 digit number.

**Making change.**Write a program that reads in a command line integer N (number of pennies) and prints the best way (fewest number of coins) to make change using US coins (quarters, dimes, nickels, and pennies only). For example, if N = 73 then print

2 quarters 2 dimes 3 pennies

*Hint*: use the greedy algorithm. That is, dispense as many quarters as possible, then dimes, then nickels, and finally pennies.

* * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *

* . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *

* . . . . . * * * . . . * * * * * . * * * * * * * * * * * * * . * * * * * . . . * * * . . . . . *

% java Diamond 4 . . . . * . . . . . . . * * * . . . . . * * * * * . . . * * * * * * * . * * * * * * * * * . * * * * * * * . . . * * * * * . . . . . * * * . . . . . . . * . . . .

for (int i = -N; i <= N; i++) { for (int j = -N; j <= N; j++) { if (i*i + j*j <= N*N) System.out.print("* "); else System.out.print(". "); } System.out.println(); }

**Seasons.**Write a program that takes two command line integers M and D and prints the season corresponding to month M (1 = January, 12 = December) and day D in the northern hemisphere. Use the following table

SEASON FROM TO Spring March 21 June 20 Summer June 21 September 22 Fall September 23 December 21 Winter December 21 March 20

**Zodiac signs.**Write a program that takes two command line integers M and D and prints the Zodiac sign corresponding to month M (1 = January, 12 = December) and day D. Use the following table

SIGN FROM TO Capricorn December 22 January 19 Aquarius January 20 February 17 Pisces February 18 March 19 Aries March 20 April 19 Taurus April 20 May 20 Gemini May 21 June 20 Cancer June 21 July 22 Leo July 23 August 22 Virgo August 23 September 22 Libra September 23 October 22 Scorpio October 23 November 21 Sagittarius November 22 December 21

**Muay Thai kickboxing.**Write a program that reads in the weight of a Muay Thai kickboxer (in pounds) as a command-line argument and prints their weight class. Use a statement.

CLASS FROM TO Flyweight 0 112 Super flyweight 112 115 Bantamweight 115 118 Super bantamweight 118 122 Featherweight 122 126 Super featherweight 126 130 Lightweight 130 135 Super lightweight 135 140 Welterweight 140 147 Super welterweight 147 154 Middleweight 154 160 Super middleweight 160 167 Light heavyweight 167 175 Super light heavyweight 175 183 Cruiserweight 183 190 Heavyweight 190 220 Super heavyweight 220 -

**Euler's sum of powers conjecture.**In 1769 Euler generalized Fermat's Last Theorem and conjectured that it is impossible to find three 4th powers whose sum is a 4th power, or four 5th powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the conjecture by finding positive integers a, b, c, d, and e such that a

^{5}+ b

^{5}+ c

^{5}+ d

^{5}= e

^{5}. Write a program Euler.java that reads in a command line parameter N and exhaustively searches for all such solutions with a, b, c, d, and e less than or equal to N. No counterexamples are known for powers greater than 5, but you can join EulerNet, a distributed computing effort to find a counterexample for sixth powers.

**Blackjack.**Write a program that takes three command line integers x, y, and z representing your two blackjack cards x and y, and the dealers face-up card z, and prints the "standard strategy" for a 6 card deck in Atlantic city. Assume that x, y, and z are integers between 1 and 10, representing an ace through a face card. Report whether the player should hit, stand, or split according to these strategy tables. (When you learn about arrays, you will encounter an alternate strategy that does not involve as many if-else statements).

**Blackjack with doubling.**Modify the previous exercise to allow

*doubling*.

**Projectile motion.**The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to print the (x, y) position of the missile at each time step t. Use trial and error to determine at what angle you should aim the missile if you hope to incinerate a target located 100 miles due east of your current location and at the same elevation. Assume the windspeed is 20 mph due east.

**World series.**The baseball world series is a best of 7 competition, where the first team to win four games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to estimate the chance that the weaker teams wins the World Series and to estimate how many games on average it will take.

**Sorting networks.**Write a program Sort3.java with three statements (and no loops) that reads in three integers

*a*,

*b*, and

*c*from the command line and prints them out in ascending order.

if (a > b) swap a and b if (a > c) swap a and c if (b > c) swap b and c

**Oblivious sorting network.**Convince yourself that the following code fragment rearranges the integers stored in the variables A, B, C, and D so that A <= B <= C <= D.

Devise a sequence of statements that would sort 5 integers. How many statements does your program use?

if (A > B) { t = A; A = B; B = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (D > E) { t = D; D = E; E = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; }

**Optimal oblivious sorting networks.**Create a program that sorts four integers using only 5 statements, and one that sorts five integers using only 9 statements of the type above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you check that your program works for all inputs?

*Solution*: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.java sorts 5 elements using 9 compare-exchanges.

The *0-1 principle* asserts that you can verify the correctness of a (deterministic) sorting algorithm by checking whether it correctly sorts an input that is a sequence of 0s and 1s. Thus, to check that works, you only need to test it on the 2^5 = 32 possible inputs of 0s and 1s.

**Optimal oblivious sorting (challenging).**Find an optimal sorting network for 6, 7, and 8 inputs, using 12, 16, and 19 statements of the form in the previous problem, respectively.

*Solution*: Sort6.java is the solution for sorting 6 elements.

**Optimal non-oblivious sorting.**Write a program that sorts 5 inputs using only 7 comparisons.

*Hint*: First compare the first two numbers, the second two numbers, and the larger of the two groups, and label them so that a < b < d and c < d. Second, insert the remaining element e into its proper place in the chain a < b < d by first comparing against b, then either a or d depending on the outcome. Third, insert c into the proper place in the chain involving a, b, d, and e in the same manner that you inserted e (with the knowledge that c < d). This uses 3 (first step) + 2 (second step) + 2 (third step) = 7 comparisons. This method was first discovered by H. B. Demuth in 1956.

**Weather balloon.**(Etter and Ingber, p. 123) Suppose that h(t) = 0.12t

^{4}+ 12t

^{3}- 380t

^{2}+ 4100t + 220 represents the height of a weather balloon at time t (measured in hours) for the first 48 hours after its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum height?

*Solution*: t = 5.

int a = 10, b = 18; if (a = b) System.out.println("equal"); else System.out.println("not equal");

*Solution*: It uses the assignment operator instead of the equality operator in the conditional. In Java, the result of this statement is an integer, but the compiler expects a boolean. As a result, the program will not compile. In some languages (notably C and C++), this code fragment will set the variable a to 18 and print without an error.

**Gotcha 1.**What does the following code fragment do?

boolean a = false; if (a = true) System.out.println("yes"); else System.out.println("no");

*Solution*: it prints . Note that the conditional uses = instead of ==. This means that is assigned the value As a result, the conditional expression evaluates to . Java is not immune to the = vs. == error described in the previous exercise. For this reason, it is much better style to use or when testing booleans.

**Gotcha 2.**What does the following code fragment do?

int a = 17, x = 5, y = 12; if (x > y); { a = 13; x = 23; } System.out.println(a);

*Solution*: Always prints 13 since there is a spurious semicolon after the statement. Thus, the assignment statement will be executed even though It is legal (but uncommon) to have a block that does not belong to a conditional statement, loop, or method.

**Gotcha 3.**What does the following code fragment do?

for (int x = 0; x < 100; x += 0.5) { System.out.println(x); }

*Solution*: It goes into an infinite loop printing . The compound assignment statement is equivalent to .

It does not compile because the compile cannot guarantee that is initialized. Use instead.

int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) rate = .33; if (income >= 114650) rate = .28; if (income >= 47450) rate = .25; if (income >= 0) rate = .22; System.out.println(rate);

**Application of Newton's method.**Write a program that finds the radii where the probability of finding the electron in the 4s excited state of hydrogen is zero. The probability is given by:

*(1 - 3r/4 + r*, where

^{2}/8 - r^{3}/192)^{2}e^{-r/2}*r*is the radius in units of the Bohr radius (0.529173E-8 cm). Use Newton's method. By starting Newton's method at different values of

*r*, you can discover all three roots.

*Hint*: use initial values of r= 0, 5, and 13.

*Challenge*: explain what happens if you use an initial value of r = 4 or 12.

**Pepys problem.**In 1693, Samuel Pepys asked Isaac Newton which was more likely: getting at least one 1 when rolling a fair die 6 times or getting at least two 1's when rolling a fair die 12 times. Write a program Pepys.java that uses simulation to determine the correct answer.

String s = ""; for (int i = 1; i <= N; i++) { if (i % 2 == 0) s = s + i + s; else s = i + s + i; }

*Solution*: Palindrome.java.

**Body mass index.**The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program that takes two command-line arguments, and , computes the BMI, and prints the corresponding BMI category:

- Starvation: less than 15
- Anorexic: less than 17.5
- Underweight: less than 18.5
- Ideal: greater than or equal to 18.5 but less than 25
- Overweight: greater than or equal to 25 but less than 30
- Obese: greater than or equal to 30 but less than 40
- Morbidly Obese: greater than or equal to 40

**Reynolds number.**The

*Reynolds number*is the ratio if inertial forces to viscous forces and is an important quantity in fluid dynamics. Write a program that takes in 4 command-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * v * rho / mu (assuming all arguments are in SI units). If the Reynold's number is less than 2000, print , if it's between 2000 and 4000, print , and if it's more than 4000, print .

**Wind chill revisited.**The wind chill formula from Exercise 1.2.14 is only valid if the wind speed is above 3MPH and below 110MPH and the temperature is below 50 degrees Fahrenheit and above -50 degrees. Modify your solution to print an error message if the user types in a value outside the allowable range.

**Point on a sphere.**Write a program to print the (x, y, z) coordinates of a random point on the surface of a sphere. Use Marsaglia' method: pick a random point (a, b) in the unit circle as in the example. Then, set x = 2a sqrt(1 - a^2 - b^2), y = 2b sqrt(1 - a^2 - b^2), z = 1 - 2(a^2 + b^2).

**Powers of k.**Write a program that takes an integer as command-line argument and prints all the positive powers of in the Java data type.

*Note*: the constant is the value of the largest integer in .

**Square root, revisited.**Why not use the loop-continuation condition in Sqrt.java instead of ?

*Solution*: Surprisingly, it can lead to inaccurate results or worse. For example, if you supply SqrtBug.java with the command-line argument , you get as the answer (instead of ); if you supply , you get an infinite loop!

double x; if (a >= 0) x = 3.14; if (a < 0) x = 2.71; System.out.println(x);

*Solution*: It complains that the variable x might not have been initialized (even though we can clearly see that x will be initialized by one of the two if statements). You can avoid this problem here by using if-else.

**Q1. Trace the following curve**

**y=x/(1+x ^{2})(5 Marks)**

Solution:

Given thaty=x/(1+x^{2})

therefore y(1+x^{2}) = x

therefore y + x^{2}y = x

therefore dy/dx + x^{2} (dy/dx) + 2xy = 1

therefore dy/dx(1+x^{2}) = 1 – 2xy

Putting the value of y

dy/dx(1+x^{2}) = 1 – 2x[x/(1+x^{2})]

= 1 – 2x^{2}/(1+x^{2})= [1 – x^{2} / 1 + x^{2}]

therefore dy/dx = [1 – x^{2} / (1 + x^{2})^{2}]

From eq^{n}(1)y=x/(1+x^{2})

So if y=0 and x=0

Then f(x,y) = y - x/(1+x^{2})= 0

Then curve

Y | 0 | 0.5 | 0.4 | 0.3 | Infinite |

x | 0 | 1 | 2 | 3 | -1 |

Curve is traced as follow

**Q2. Obtain fifth roots of 4+3i. (5 Marks)**

Solution:

Given Complex number is Z = 4 + 3i

**Q3. Prove that |4x – 5y| <= 4|x| + 5|y|(5 Marks)**

Solution:

L.H.S = |4x – 5y|

= (|4x – 5y|^{2})(because |x|^{2} = x for all x belong R)

= (4x – 5y)

Therefor |4x|^{2} + |5y|^{2} – 2|4x|.|5y|

= > (|4x| + |5y|)^{2} - 2|4x|.|5y|

Since |x|>= 0 for all x belong R

So taking square on both side

|4x – 5y| <= 4|x| + 5|y|

Given equation is

5x^{3} – 8x^{2} + 7x + 6 = 0

= > x^{3} – (8/5)x^{2} + (7/5)x + (6/5) = 0-----------(1)

Let a, b, c are the roots, so

a + b + c = 8/5-------------------(2)

ab + bc + ca = 7/5--------------------(3)

abc = -6/5--------------------(4)

Now Let roots of cubic equation is p, q, r such that

p = a^{2 }+ b^{2} + ba-------------------(5)

q = b^{2} +c^{2} + cb---------------------(6)

r = c^{2} + a^{2} + ca--------------------(7)

Then cube equation is

(x - p)(x - q)(x - r) = 0

= > (x - p)[x^{2} – (q + r)x + qr] = 0

= > x^{3} – x^{2} (p+q+r) + x(pq+qr+rp) – pqr = 0------------(8)

Now(p+q+r) = 2(a^{2} + b^{2} + c^{2}) + ab + bc + ca

= >(p+q+r) = 2[(a + b + c)^{2} – 2(ab + bc + ca)] + ab + bc + ca

= >(p+q+r) = 2(a + b + c)^{2} – 3(ab + bc + ca)

= >(p+q+r) = 2(8/5)^{2} – 3*(7/5)

= >(p+q+r) = 23/25-----------------------(9)

Similarly,pq+qr+rp = (a^{2} + b^{2} + ab)(b^{2 }+ c^{2} + bc)

= a^{2}b^{2} + a^{2}c^{2} + a^{2}bc + b^{4} + b^{2}c^{2} + b^{3}c + ab^{3} + abc^{2} + ab^{2}c

We can use,( a^{2} + b^{2} + c^{2})2 = a^{4} + b^{4} + c^{4} + 2(a^{2}b^{2} + b^{2}c^{2} + c^{2}a^{2})

Write equation in term of a^{2}, b^{2} and c^{2}

Putting the value from (5), (6) and (7) we get

pq+qr+rp = 22/25-------------------(10)

and pqr =-21/25--------------------(11)

putting the value of (9), (10) and (11) in (8)

= > x^{3} – x^{2} (23/25) + x(22/25) – (-21/25) = 0

= > 25x^{3} – 23x^{2} + 22x – 21 = 0

**Q5. Find the perimeter of the cord**

**Solution:**

## Leave a Comment

(0 Comments)