Preview only show first 10 pages with watermark. For full document please download

Computer Science 2

   EMBED

  • Rating

  • Date

    December 1969
  • Size

    9.9MB
  • Views

    8,030
  • Categories


Share

Transcript

2511 For the Gauss-gamma posterior p ( μ, λ | μ 0 , α, β, X ) given in Equation (8.8.28) compute the marginal posterior p ( μ | μ 0 , α, β, X ). What is the mean of this distribution? 2512 26. This exercise concerns the derivation of Equation (8.4.15). 1. By considering p(y)= p ( y | x ) p ( x ) d x (8.11.47) 1T 1 1T −1 ∝ show that exp − 2 ( y − Mx − μ ) I: − ( y − Mx − μ ) − 2 ( x − μ x ) I: x ( x − μ x ) d x (8.11.48) 1 1 TT p ( y ) ∝ exp  2 y I: y 2 x Ax + x ( By + c ) exp  (8.11.49) for suitably defined A , B , c . 2. Using Equation (8.4.13), show that T −1 1 T−11 T −1 p ( y ) ∝ exp  2 y I: y − 2 ( By + c ) A ( By + c ) . 3. This establishes that p ( y ) is Gaussian. We now need to find the mean and covariance of this Gaussian. We can do this by the lengthy process of completing the square. Alternatively, we can appeal to ( y ) = M ( x ) + ( η ) = M μ x+ μ . By considering ( y − ( y ) ) ( y − ( y ) ) T  = ( Mx + η − M μ x  μ ) ( Mx + η − M μ x − μ ) T (8.11.50) and the independence of x and η , derive the formula for the covariance of p ( y ). 2513 32. Show that for the whitened data matrix, given in Equation (8.4.30), ZZ T = N I . 32. Consider a uniform distribution p i = 1 /N defined on states i = 1 ,...,N . Show that the entropy of this distribution is N H =− i =1 p i log p i = log N (8.11.61) and that therefore as the number of states N increases to infinity, the entropy diverges to infinity. 2514 For variables x , y , and z = x + y , show that the correlation coefficients are related by ρ x,z ≥ ρ x,y . With reference to the correlation coefficient as the angle between two vectors, explain why ρ x,z ≥ ρ x,y is geometrically obvious. 2515 38. Consider a ‘Boltzman machine’ distribution on binary variables x i ∈ { 0 , 1 } , i = 1 ,...,D 1T p ( x | W ) = Z ( W ) exp x Wx (8.11.81) p and that we wish to fit another distribution q of the same form to p 1T q ( x | U ) = Z ( U ) exp x Ux . (8.11.82) q 1. Show that argmin KL( p | q ) = argmax trace ( UC ) − log Z q ( U ) , C ij ≡ ( x i x j ) p . (8.11.83) UU 2. Hence show that knowing the ‘cross moment’ matrix C of p is sufficient to fully specify p . 2. Generalise the above result to all models in the exponential family. 2516 1. 1. Give an example of a two-dimensional dataset for which the data are linearly separable, but not linearly independent. 2. Can you find a dataset which is linearly independent but not linearly separable? 2517 2. Show that for both ordinary and orthogonal least squares regression fits to data ( x n , y n ) ,n = 1 ,...,N ) the fitted lines go through the point ), N n1 = ( x n , y n ) /N . 2518 4. Derive from Equation (17.5.9) the dual optimisation problem Equation (17.5.15). 4. A datapoint x is projected to a lower-dimensional vector x ´ using x ´ = Mx (17.9.4) where M is a given ‘fat’ (short and wide) matrix. For a set of data { x n ,n = 1 ,...,N } and corresponding binary class labels y n ∈ { 0 , 1 } , using logistic regression on the projected datapoints x ´ n corresponds to a form of constrained logistic regression in the original higher-dimensional space x . Explain if it is reasonable to use an algorithm such as PCA to first reduce the data dimensionality before using logistic regression. 2519 6. The logistic sigmoid function is defined as σ ( x ) = e x / (1 + e x ). What is the inverse function, σ − 1 ( x )? 6. Given a dataset D = { ( x n , c n ) ,n = 1 ,...,N } , where c n ∈ { 0 , 1 } , logistic regression uses the model p ( c = 1| x) = σ ( w T x + b ). Assuming the data is drawn independently and identically, show that the derivative of the log likelihood L with respect to w is N ∇ w L = c n − σ w T x n + b x n . (17.9.5) n =1 2520 Consider a dataset D = { ( x n , c n ) ,n = 1 ,...,N } , where c n ∈ { 0 , 1 } , and x is a D -dimensional vector. Show that if the training data is linearly separable with the hyperplane w T x + b , the data is also separable with the hyperplane w ˜ T x + b ˜ , where w ˜ 1. = λ w , b ˜ = λb for any scalar λ > 0. 2. What consequence does the above result have for maximum likelihood training of logistic regression for linearly separable data? 2521 Consider a dataset D = { ( x n ,c n ) ,n = 1 ,...,N } , where c n ∈ { 0 , 1 } , and x is an N -dimensional vector. Hence we have N datapoints in an N - dimensional space. In the text we showed that to find a hyperplane (parameterised by w and b ) that linearly separates this data we need, for each datapoint x n ,w T x n +b=r n where r n > 0 for c n = 1 and r n 0 for c n = 0. Furthermore, we suggested an algorithm to find such a hyperplane. Comment on the relation between maximum likelihood training of logistic regression and the algorithm suggested above. 2522 For the undirected graph on the square lattice as shown, draw a triangulated graph with the smallest clique sizes possible. 2523 7. Consider a binary variable Markov random field p ( x ) = Z − 1 n i > j φ ( x i , x j ), defined on the n × n lattice with φ ( x i , x j ) = e I [ x i = x j ] for ia neighbour of jon the lattice and i > j . A naive way to perform inference is to first stack all the variables in the t th column and call this cluster variable X t , as shown. The resulting graph is then singly connected. What is the complexity of computing the normalisation constant based on this cluster representation? Compute log Z for n= 10. 2524 Given a consistent junction tree on which a full round of message passing has occurred, explain how to form a belief network from the junction tree. 2525 9.The file diseaseNet.mat contains the potentials for a disease bi-partite belief network, with 20 diseases d 1 ,...,d 20 and 40 symptoms, s 1 ,..., s 40 . The disease variables are numbered from 1 to 20 and the Symptoms from 21 to 60. Each disease and symptom is a binary variable, and each symptom connects to 3 parent diseases. 1. Using the BRMLtoolbox, construct a junction tree for this distribution and use it to compute all the marginals of the symptoms, p ( s i = 1). 2. Explain how to compute the marginals p ( s i = 1) in a more efficient way than using the junction tree formalism. By implementing this method, compare it with the results from the junction tree algorithm. 3. Symptoms 1 to 5 are present (state 1), symptoms 6 to 10 not present (state 2) and the rest are not known. Compute the marginal p ( d i = 1| s 1:10 ) for all diseases. 2526 10. Consider the distribution T p ( y | x 1 ,..., x T ) p ( x 1 ) n p ( x t | x t − 1 ) t =2 where all variables are binary. 1. Draw a junction tree for this distribution and explain the computational complexity of computing p ( x T ), as suggested by the junction tree algorithm. 2. By using an approach different from the plain JTA above, explain how p ( x T ) can be computed in time that scales linearly with T . 2527 11. Analogous to jtpot=absorption(jtpot,jtsep,infostruct), write a routine [jtpot jtmess]=ShaferShenoy(jtpot,infostruct) that returns the clique marginals and messages for a junction tree under Shafer–Shenoy updating. Modify demoJTree.m to additionally output your results for marginals and conditional marginals alongside those obtained using absorption. 2528 Show that the Markov network 1 2 3 1. labelling for this graph. 2529 2.Consider the following distribution: is not perfect elimination ordered and give a perfect elimination p ( x 1 , x 2 , x 3 , x 4 ) = φ ( x 1 , x 2 ) φ ( x 2 , x 3 ) φ ( x 3 , x 4 ) . (6.12.1) 1. Draw a clique graph that represents this distribution and indicate the separators on the graph. 2. Write down an alternative formula for the distribution p ( x 1 , x 2 , x 3 , x 4 ) in terms of the marginal probabilities p ( x 1 , x 2 ), p ( x 2 , x 3 ), p ( x 3 , x 4 ), p ( x 2 ), p ( x 3 ) . 2530 7. i > j Consider a binary variable Markov random field p ( x ) = Z − 1 n φ ( x i , x j ), defined on the n × n lattice with φ ( x i , x j ) = e I [ x i = x j ] for ia neighbour of jon the lattice and i > j . A naive way to perform inference is to first stack all the variables in the t th column and call this cluster variable X t , as shown. The resulting graph is then singly connected. What is the complexity of computing the normalisation constant based on this cluster representation? Compute log Z for n= 10. 2531 Given a consistent junction tree on which a full round of message passing has occurred, explain how to form a belief network from the junction tree. 2532 9.The file diseaseNet.mat contains the potentials for a disease bi-partite belief network, with 20 diseases d 1 ,...,d 20 and 40 symptoms, s 1 ,..., s 40 . The disease variables are numbered from 1 to 20 and the Symptoms from 21 to 60. Each disease and symptom is a binary variable, and each symptom connects to 3 parent diseases. 1. Using the BRMLtoolbox, construct a junction tree for this distribution and use it to compute all the marginals of the symptoms, p ( s i = 1). 2. Explain how to compute the marginals p ( s i = 1) in a more efficient way than using the junction tree formalism. By implementing this method, compare it with the results from the junction tree algorithm. 3. Symptoms 1 to 5 are present (state 1), symptoms 6 to 10 not present (state 2) and the rest are not known. Compute the marginal p ( d i = 1| s 1:10 ) for all diseases. 2533 10. Consider the distribution T p ( y | x 1 ,..., x T ) p ( x 1 ) n p ( x t | x t − 1 ) t =2 where all variables are binary. 1. Draw a junction tree for this distribution and explain the computational complexity of computing p ( x T ), as suggested by the junction tree algorithm. 2. By using an approach different from the plain JTA above, explain how p ( x T ) can be computed in time that scales linearly with T . 2534 11. Analogous to jtpot=absorption(jtpot,jtsep,infostruct), write a routine [jtpot jtmess]=ShaferShenoy(jtpot,infostruct) that returns the clique marginals and messages for a junction tree under Shafer–Shenoy updating. Modify demoJTree.m to additionally output your results for marginals and conditional marginals alongside those obtained using absorption. 2535 5. You are given that x ⊥ y |( z, u ) , u ⊥ z | ∅ . (4.8.8) Derive the most general form of probability distribution p ( x, y, z, u ) consistent with these statements. Does this distribution have a simple graphical model? 2536 Consider the belief network on the right. 1. Write down a Markov network of p ( x 1 , x 2 , x 3 ). 2. Is your Markov network a perfect map of p ( x 1 , x 2 , x 3 )? 2527 5. Two research labs work independently on the relationship between discrete variables x and y . Lab A proudly announces that they have ascertained distribution p A ( x | y ) from data. Lab B proudly announces that they have ascertained p B ( y | x ) from data. 1. Is it always possible to find a joint distribution p ( x, y ) consistent with the results of both labs? Is it possible to define consistent marginals p ( x ) and p ( y ), in the sense that p ( x ) = J, y p A ( x | y ) p ( y ) 2. and p ( y ) = J, x p B ( y | x ) p ( x )? If so, explain how to find such marginals. If not, explain why not. 2538 Research lab A states its findings about a set of variables x 1 ,..., x n as a list L A of conditional independence statements. Lab B similarly provides a list of conditional independence statements L B . 1. Is it always possible to find a distribution which is consistent with L A and L B ? 2. If the lists also contain dependence statements, how could one attempt to find a distribution that is consistent with both lists? 2539 5.Consider the distribution p ( x, y, w, z ) = p ( z | w ) p ( w | x, y ) p ( x ) p ( y ) . (4.8.10) 1. Write p ( x | z ) using a formula involving (all or some of) p ( z | w ), p ( w | x, y ), p ( x ), p ( y ). 2. Write p ( y | z ) using a formula involving (all or some of) p ( z | w ), p ( w | x, y ), p ( x ), p ( y ). 3. Using the above results, derive an explicit condition for x ⊥ y | z and explain if this is satisfied for this distribution. 2540 5.Consider the distribution p ( t 1 , t 2 , y 1 , y 2 , h ) = p ( y 1 | y 2 , t 1 , t 2 , h ) p ( y 2 | t 2 , h ) p ( t 1 ) p ( t 2 ) p ( h ) . (4.8.11) 1. Draw a belief network for this distribution. 2. Does the distribution p ( t 1 , t 2 , y 1 , y 2 ) = ) p ( y 1 | y 2 , t 1 , t 2 , h ) p ( y 2 | t 2 , h ) p ( t 1 ) p ( t 2 ) p ( h ) (4.8.12) h have a perfect map belief network? 3. Show that for p ( t 1 , t 2 , y 1 , y 2 ) as defined above t 1 ⊥ y 2 | ∅. 2541 5.Consider the distribution p ( a, b, c, d ) = φ ab ( a, b ) φ bc ( b, c ) φ cd ( c, d ) φ da ( d, a ) (4.8.13) where the φ are potentials. 1. Draw a Markov network for this distribution. 2. Explain if the distribution can be represented as a (‘non-complete’) belief network. 3. Derive explicitly if a ⊥ c | ∅. 2542 5. Show how for any singly connected Markov network, one may construct a Markov equivalent belief network. 5. Consider a pairwise binary Markov network defined on variables s i ∈ { 0 , 1 } , i = 1 ,...,N , with p ( s ) = n ij ∈ E φ ij ( s i , s j ), where E is a given edge set and the potentials φ ij are arbitrary. Explain how to translate such a Markov network into a Boltzmann machine. 2543 1. (Party animal) The party animal problem corresponds to the network in Fig. 3.14. The boss is angry and the worker has a headache – what is the probability the worker has been to a party? To complete the specifications, the probabilities are given as follows: p ( U = tr| P = tr ,D = tr) = 0 . 999 p ( U = tr| P = fa ,D = tr) = 0 . 9 p ( H = tr| P = tr) = 0 . 9 p ( U = tr| P = tr ,D = fa) = 0 . 9 p ( U = tr| P = fa ,D = fa) = 0 . 01 p ( H = tr| P = fa) = 0 . 2 p ( A = tr| U = tr) = 0 . 95 p ( A = tr| U = fa) = 0 . 5 p ( P = tr) = 0 . 2 , p ( D = tr) = 0 . 4 2544 2. Consider the distribution p ( a, b, c ) = p ( c | a, b ) p ( a ) p ( b ). (i) Is a ⊥ b | ∅? (ii) Is a ⊥ b | c ? x = Positive X-ray d = Dyspnea (shortness of breath) e = Either tuberculosis or lung cancer t = Tuberculosis l = Lung cancer b = Bronchitis a = Visited Asia s = Smoker Figure 3.15 Belief network structure for the Chest Clinic example. 2545 The Chest Clinic network [184] concerns the diagnosis of lung disease (tuberculosis, lung cancer, or both, or neither), see Fig. 3.15. In this model a visit to Asia is assumed to increase the probability of tuberculosis. State if the following conditional independence relationships are true or false 1. tuberculosis⊥ smoking| shortness of breath 2. lung cancer⊥ bronchitis| smoking 3. visit to Asia ⊥ smoking| lung cancer 4. visit to Asia ⊥ smoking| lung cancer , shortness of breath 2546 4. Consider the Chest Clinic belief network in Fig. 3.15 [184]. Calculate by hand the values for p ( d ), p ( d | s = tr),p ( d | s = fa). The table values are: p ( a = tr) = 0 . 01 p ( s = tr) =0.5 p ( t = tr| a = tr) = 0 . 05 p ( t = tr| a = fa) = 0 . 01 p ( l = tr| s = tr) =0.1 p ( l = tr| s = fa) = 0 . 01 p ( b = tr| s = tr) =0.6 p ( b = tr| s = fa) =0.3 p ( x = tr| e = tr) = 0 . 98 p ( x = tr| e = fa) = 0 . 05 p ( d = tr| e = tr ,b = tr) = 0 . 9 p ( d = tr| e = tr ,b = fa) = 0 . 7 p ( d = tr| e = fa ,b = tr) = 0 . 8 p ( d = tr| e = fa ,b = fa) = 0 . 1 p ( e = tr| t, l ) = 0 only if botht andl are fa, 1 otherwise. 2547 5. If we interpret the Chest Clinic network Exercise 3.4 causally, how can we help a doctor answer the question ‘If I could cure my patients of bronchitis, how would this affect my patients’ chance of being short of breath?’. How does this compare with p ( d = tr| b = fa) in a non-causal interpretation, and what does this mean? 2548 6. ([140]) The network in Fig. 3.16 concerns the probability of a car starting, with p ( b = bad) = 0 . 02 p ( f = empty) = 0 . 05 p ( g = empty| b = good ,f = not empty) = 0 . 04 p ( g = empty| b = good ,f = empty) = 0 . 97 p ( g = empty| b = bad ,f = not empty) = 0 . 1 p ( g = empty| b = bad ,f = empty) = 0 . 99 p ( t = fa| b = good) = 0 . 03 p ( t = fa| b = bad) = 0 . 98 p ( s = fa| t = tr ,f = not empty) = 0 . 01 p ( s = fa| t = tr ,f = empty) = 0 . 92 p ( s = fa| t = fa ,f = not empty) = 1 . 0 p ( s = fa| t = fa ,f = empty) = 0 . 99 Calculate P ( f = empty| s = no ), the probability of the fuel tank being empty conditioned on the obser- vation that the car does not start. 2549 7.There is a synergistic relationship between Asbestos (A) exposure, Smoking (S) and Cancer (C). A model describing this relationship is given by p ( A, S, C ) = p ( C | A, S ) p ( A ) p ( S ) . (3.7.1) Figure 3.16 Belief network of car starting, see Exercise 3.6. Is A ⊥ S | ∅? 1. Is A ⊥ S | C ? 2. 3. How could you adjust the model to account for the fact that people who work in the building industry have a higher likelihood to also be smokers and also a higher likelihood to be exposed to asbestos? 2550 8.Consider the belief network on the right which represents Mr Holmes’ burglary worries as given in Fig. 3.3(a): (B)urglar, (A)larm, (W)atson, Mrs (G)ibbon. All variables are binary with states { tr , fa } . The table entries are p ( B = tr) = 0 . 01 p ( A = tr| B = tr) = 0 . 99 p ( A = tr| B = fa) = 0 . 05 p ( W = tr| A = tr) = 0 . 9 p ( W = tr| A = fa) = 0 . 5 p ( G = tr| A = tr) = 0. 7 p ( G = tr| A = fa) = 0 . 2 1. Compute ‘by hand’ (i.e. show your working): 1. p ( B = tr| W = tr) 2. p ( B = tr| W = tr ,G = fa) (3.7.2) 2. Consider the same situation as above, except that now the evidence is uncertain. Mrs Gibbon thinks that the state is G = fa with probability 0.9. Similarly, Dr Watson believes in the state W = fa with value 0.7. Compute ‘by hand’ the posteriors under these uncertain (soft) evidences: 2551 1. p ( B = tr| W ˜ ) 2. p ( B = tr| W ˜ , G ˜ ) A doctor gives a patient a (D)rug (drug or no drug) dependent on their (A)ge (old or young) and (G)ender (male or female). Whether or not the patient (R)ecovers (recovers or doesn’t recover) depends on all D, A, G . In addition A ⊥ G | ∅. 1. Write down the belief network for the above situation. 2. Explain how to compute p (recover|drug). 3. Explain how to compute p (recover| do (drug) , young). 2552 10. mplement the Wet Grass scenario in Section 3.1.1 using the BRMLtoolbox. 10. (LA Burglar) Consider the Burglar scenario, Example 3.1. We now wish to model the fact that in Los Angeles the probability of being burgled increases if there is an earthquake. Explain how to include this effect in the model. 2553 Given two belief networks represented as DAGs with associated adjacency matrices A and B , write a MATLAB function MarkovEquiv(A,B).m that returns 1 if A and B are Markov equivalent, and zero otherwise. 2554 13. The adjacency matrices of two belief networks are given below (see ABmatrices.mat). State if they are Markov equivalent. ⎛0 ⎜0 ⎜0 ⎜ ⎜0 ⎜ A=⎜ 0 1 1 0 1 0 0 0 ⎞⎛0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 0 ⎟⎜0 0 1 0 0 0 0 0 00 0 0 0 0 1 0 1⎟ ⎜0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 ⎟⎜ 0 ⎞ 0 ⎟ ⎟⎜ 0 0 0 0 0 0 1 ⎟⎜ ⎟ ⎟ 0 ⎟ ⎟ 1 0 1 0 0 0 1 0 0 ⎟, B = ⎜0 1 1 0 0 0 1 0 0 ⎟. ⎟⎜⎟ 0 ⎜ ⎜ ⎜ 000100010 ⎟ ⎟ ⎜ ⎜ ⎟ ⎟ ⎜ 0 0 1 0 0 0 1 0⎟ ⎜⎟1 ⎜ 000000001⎟ ⎜ 000000001⎟ ⎜⎟⎜⎟ ⎜ 000000000⎟ ⎜ 000000000⎟ ⎝⎠⎝⎠ 000000000 000000000 (3.7.3) 2555 14. There are three computers indexed by i ∈ { 1 , 2 , 3 } . Computer i can send a message in one timestep to computer j if C ij = 1, otherwise C ij = 0. There is a fault in the network and the task is to find out some information about the communication matrix C ( C is not necessarily symmetric). To do this, Thomas, the engineer, will run some tests that reveal whether or not computer i can send a message to computer j in ttimesteps, t ∈ { 1 , 2 } . This is expressed as C ij ( t ), with C ij (1) ≡ C ij . For example, he might know that C 13 (2) = 1, meaning that according to his test, a message sent from computer 1 will arrive at computer 3 in at most two timesteps. Note that this message could go via different routes – it might go directly from 1 to 3 in one timestep, or indirectly from 1 to 2 and then from 2 to 3, or both. You may assume C ii = 1. A priori Thomas thinks there is a 10% probability that C ij = 1, i /= j , and assumes that each such connection is independent of the rest. Given the test information C = { C 12 (2) = 1 , C 23 (2) = 0 } , compute the a posteriori probability vector [ p ( C 12 = 1| C ) , p ( C 13 = 1| C ) , p ( C 23 = 1| C ) , p ( C 32 = 1| C ) ,p ( C 21 = 1| C ) , p ( C 31 = 1| C )] . (3.7.4) 2556 15. A belief network models the relation between the variables oil, inf, eh, bp, rt which stand for the price of oil, inflation rate, economy health, British Petroleum Stock price, retailer stock price. Each variable takes the states low , high, except for bp which has states low , high , normal. The belief network model for these variables has tables p ( eh =low)=0.2 p ( bp =low| oil =low)=0.9 p ( bp =normal| oil =low)=0.1 p ( bp =low| oil =high)=0.1 p ( bp =normal| oil =high)=0.4 p ( oil =low| eh =low)=0.9 p ( oil =low| eh =high)=0.05 p ( rt =low| inf =low, eh=low)=0.9 p ( rt =low| inf =low, eh=high)=0.1 p ( rt =low| inf =high, eh=low)=0.1 p ( rt =low| inf =high, eh=high)=0.01 p ( inf =low| oil =low, eh=low)=0.9 p ( inf =low| oil =low, eh=high)=0.1 p ( inf =low| oil =high, eh=low)=0.1 p ( inf =low| oil =high, eh=high)=0.01 1. Draw a belief network for this distribution. 2. Given that the BP stock price is normal and the retailer stock price is high, what is the probability that inflation is high? 2557 There is a set of C potentials with potential c defined on a subset of variables X c . If X c ⊆ X d we can merge (multiply) potentials c and d since the variables in potential c are contained within potential d . With reference to suitable graph structures, describe an efficient algorithm to merge a set of potentials so that for the new set of potentials no potential is contained within the other. 2558 Alice and Bob share a bank account which contains an a priori unknown total amount of money T . Whenever Alice goes to the cash machine, the available amount for withdrawal A for Alice is always 10% of the total T . Similarly, when Bob goes to the cash machine the available amount for withdrawal B for Bob is 10% of the total T . Whatever the amount in the bank, Alice and Bob check their available amounts for withdrawal independently. Draw a belief network that expresses this situation and show that A T B . 2559 Assume that the day of the week that females are born on, x , is independent of the day of the week, y , on which males are born. Assume, however, that the old rhyme is true and that personality is dependent on the day of the week you’re born on. If a represents the female personality type and b the male personality type, then a T x and b T y , but a ⊥ b . Whether or not a male and a female are married, m , depends strongly on their personality types, m T { a, b } , but is independent of x and y if we know a and b . Draw a belief network that can represent this setting. What can we say about the (graphical) dependency between the days of the week that John and Jane are born on, given that they are not married? 2560 1. Consider an adjacency matrix A with elements [ A ] ij = 1 if one can reach state i from state j in one timestep, and 0 otherwise. Show that the matrix r A k l ij represents the number of paths that lead from state j to i in k timesteps. Hence derive an algorithm that will find the minimum number of steps to get from state j to state i . 2561 2. For an N × N symmetric adjacency matrix A , describe an algorithm to find the connected components. You may wish to examine connectedComponents.m. 2. Show that for a connected graph that is singly connected, the number of edges E must be equal to the number of nodes minus 1, E = V − 1. Give an example graph with E = V − 1 that is not singly connected. Hence the condition E = V − 1 is a necessary but not sufficient condition for a graph to be singly connected. 2562 4. Describe a procedure to determine if a graph is singly connected. 4. Describe a procedure to determine all the ancestors of a set of nodes in a DAG. 4. WikiAdjSmall.mat contains a random selection of 1000 Wiki authors, with a link between two authors if they ‘know’ each other (see snap.stanford.edu/data/wiki-Vote.html). Plot a histogram of the separation (the length of the path between two users on the graph corresponding to the adjacency matrix) between all users based on separations from 1 to 20. That is the 2563 7. The file cliques.mat contains a list of 100 non-maximal cliques defined on a graph of 10 nodes. Your task is to return a set of unique maximal cliques, eliminating cliques that are wholly contained within another. Once you have found a clique, you can represent it in binary form as, for example (1110 011110) which says that this clique contains variables 1 , 2 , 3 , 6 , 7 , 8 , 9, reading from left to right. Converting this binary representation to decimal (with the rightmost bit being the units and the leftmost 2 9 ) this corresponds to the number 926. Using this decimal representation, write the list of unique cliques, ordered from lowest decimal representation to highest. Describe fully the stages of the algorithm you use to find these unique cliques. Hint: you may find examining uniquepots.m useful. 2564 8. Explain how to construct a graph with N nodes, where N is even, that contains at least ( N/ 2) 2 maximal cliques. 8. Let N be divisible by 3. Construct a graph with N nodes by partitioning the nodes into N/ 3 subsets, each subset containing 3 nodes. Then connect all nodes, provided they are not in the same subset. Show that such a graph has 3 N/ 3 maximal cliques. This shows that a graph can have an exponentially large number of maximal cliques [217]. 2565 1. Prove p ( x, y | z ) = p ( x | z ) p ( y | x, z ) (1.6.1) and also p ( x | y, z ) = p ( y | x, z ) p ( x | z ) . (1.6.2) p(y|z) 2566 2. Prove the Bonferroni inequality p ( a, b ) ≥ p ( a ) + p ( b ) − 1 . (1.6.3) 2567 (Adapted from [181]) There are two boxes. Box 1 contains three red and five white balls and box 2 contains two red and five white balls. A box is chosen at random p ( box = 1) = p ( box = 2) = 0 . 5 and a ball chosen at random from this box turns out to be red. What is the posterior probability that the red ball came from box 1? 2568 (Adapted from [181]) Two balls are placed in a box as follows: A fair coin is tossed and a white ball is placed in the box if a head occurs, otherwise a red ball is placed in the box. The coin is tossed again and a red ball is placed in the box if a tail occurs, otherwise a white ball is placed in the box. Balls are drawn from the box three times in succession (always with replacing the drawn ball back in the box). It is found that on all three occasions a red ball is drawn. What is the probability that both balls in the box are red? 2569 (From David Spiegelhalter understandinguncertainty.org) A secret government agency has devel- oped a scanner which determines whether a person is a terrorist. The scanner is fairly reliable; 95% of all scanned terrorists are identified as terrorists, and 95% of all upstanding citizens are identified as such. An informant tells the agency that exactly one passenger of 100 aboard an aeroplane in which you are seated is a terrorist. The agency decides to scan each passenger and the shifty-looking man sitting next to you is the first to test positive. What are the chances that this man is a terrorist? 2770 6. Consider three variable distributions which admit the factorisation p ( a, b, c ) = p ( a | b ) p ( b | c ) p ( c ) (1.6.4) where all variables are binary. How many parameters are needed to specify distributions of this form? 2571 Repeat the Inspector Clouseau scenario, Example 1.3, but with the restriction that either the Maid or the Butler is the murderer, but not both. Explicitly, the probability of the Maid being the murderer and not the Butler is 0.04, the probability of the Butler being the murderer and not the Maid is 0.64. Modify demoClouseau.m to implement this. 2572 8. Prove p ( a, ( b or c )) = p ( a, b ) + p ( a, c ) − p ( a, b, c ) . (1.6.5) 2573 9. Prove p ( x | z ) = ) p ( x | y, z ) p ( y | z ) = ) p ( x | w, y, z ) p ( w | y, z ) p ( y | z ) . (1.6.6) y y,w 2574 As a young man Mr Gott visits Berlin in 1969. He’s surprised that he cannot cross into East Berlin since there is a wall separating the two halves of the city. He’s told that the wall was erected eight years previously. He reasons that: The wall will have a finite lifespan; his ignorance means that he arrives uniformly at random at some time in the lifespan of the wall. Since only 5% of the time one would arrive in the first or last 2.5% of the lifespan of the wall he asserts that with 95% confidence the wall will survive between 8 / 0 . 975 ≈ 8 . 2 and 8 /0 . 025 = 320 years. In 1989 the now Professor Gott is pleased to find that his prediction was correct and promotes his prediction method in prestigious journals. This ‘delta-t’ method is widely adopted and used to form predictions in a range of scenarios about which researchers are ‘totally ignorant’. Would you ‘buy’ a prediction from Professor Gott? Explain carefully your reasoning. 2575 11. Implement the soft XOR gate, Example 1.7 using BRMLtoolbox. You may find condpot.m of use. 11. Implement the hamburgers, Example 1.2 (both scenarios) using BRMLtoolbox. To do so you will need to define the joint distribution p ( hamburgers,KJ ) in which dom( hamburgers ) = dom ( KJ ) = { tr , fa } . 2576 13. Implement the two-dice example, Section 1.3.1 using BRMLtoolbox. 13. A redistribution lottery involves picking the correct four numbers from 1 to 9 (without replacement, so 3,4,4,1 for example is not possible). The order of the picked numbers is irrelevant. Every week a million people play this game, each paying £1 to enter, with the numbers 3,5,7,9 being the most popular (1 in every 100 people chooses these numbers). Given that the million pounds prize money is split equally between winners, and that any four (different) numbers come up at random, what is the expected amount of money each of the players choosing 3,5,7,9 will win each week? The least popular set of numbers is 1,2,3,4 with only 1 in 10 000 people choosing this. How much do they profit each week, on average? Do you think there is any ‘skill’ involved in playing this lottery? 2577 In a test of ‘psychometry’ the car keys and wristwatches of five people are given to a medium. The medium then attempts to match the wristwatch with the car key of each person. What is the expected number of correct matches that the medium will make (by chance)? What is the probability that the medium will obtain at least one correct match? 2578 16. ) 1. Show that for any function f p ( x | y ) f ( y ) = f ( y ) . (1.6.7) x 2. Explain why, in general, ) p ( x | y ) f ( x, y ) I= ) f ( x, y ) . (1.6.8) xx 2579 (Inspired by singingbanana.com). Seven friends decide to order pizzas by telephone from Pizza4U based on a flyer pushed through their letterbox. Pizza4U has only four kinds of pizza, and each person chooses a pizza independently. Bob phones Pizza4U and places the combined pizza order, simply stating how many pizzas of each kind are required. Unfortunately, the precise order is lost, so the chef makes seven randomly chosen pizzas and then passes them to the delivery boy. 1. How many different combined orders are possible? 2. What is the probability that the delivery boy has the right order? 2580 Sally is new to the area and listens to some friends discussing about another female friend. Sally knows that they are talking about either Alice or Bella but doesn’t know which. From previous conversations Sally knows some independent pieces of information: She’s 90% sure that Alice has a white car, but doesn’t know if Bella’s car is white or black. Similarly, she’s 90% sure that Bella likes sushi, but doesn’t know if Alice likes sushi. Sally hears from the conversation that the person being discussed hates sushi and drives a white car. What is the probability that the friends are talking about Alice? 2581 The weather in London can be summarised as: if it rains one day there’s a 70% chance it will rain the following day; if it’s sunny one day there’s a 40% chance it will be sunny the following day. 1. 2. Assuming that the prior probability it rained yesterday is 0.5, what is the probability that it was raining yesterday given that it’s sunny today? If the weather follows the same pattern as above, day after day, what is the probability that it will rain on any day (based on an effectively infinite number of days of observing the weather)? 3. Use the result from part 2 above as a new prior probability of rain yesterday and recompute the probability that it was raining yesterday given that it’s sunny today. 2582 If we start our function call with default arguments means, what will be proceeding arguments? 2583 please make sure to follow an instruction which attached on files. Document Preview: Assignment 2 Rubrics T1 Task 1 2 Marks 2 Marks 5 Marks Specify your protocol by listing the messages exchanged and the action taken by the automatic teller machine or the bank’s centralized computer on transmission and receipt of messages Prev. + Explicitly state the assumptions made by your protocol about the underlying end-to-end transport service Prev. + Draw a figure that shows the operation of your protocol for the case of simple withdrawal with no errors, using a time diagram. T2 Task 2 1 Marks 2 Marks 3 Marks Define TCP and UDP Prev. + Compare TCP and UDP Prev. + Contrast TCP and UDP T3 Task 3 1 Mark 2 Marks Define the way of message addressing Prev. + Suppose Host A to Host B have source port number x and destination port number y. What are the source and destination port numbers for the segments travelling from Host B to Host A? T4 Task 4 1 Mark 2 Marks 4 Marks Describe sequence numbers and acknowledgement numbers in TCP Prev. + How much data is in the first segment? Prev. + Identify the new acknowledgement number. T5 Task 5 2 Marks 4 Marks 6 Marks 8 Marks 10 Marks Calculate the checksum and show all work Prev. + Explain why your protocol takes the 1's complement of the sum and not just use the sum? Prev. + Show how, with the 1's compliment scheme, the receiver detects errors Prev. + Provide your answer and substantiate whether it possible that a onebit error will go undetected Prev. + Provide your answer and substantiate whether it possible that a two-bit error will go undetected T6 Task 6 2 Mark 5 Marks 8 Marks Describe causes of network flooding and define flow control Prev. + Draw the Finite State Machine (FSM) of a protocol that provides sliding window flow control in a reliable network Prev. + Draw a time diagram that shows the protocol behaviour in time. Assume that the window size is n T7 Task 7 1 Mark 3 Marks 5 Marks Describe causes of congestions in networks Prev. + Describe the basic idea of TCP congestion control Prev. + Demonstrate that the... Attach 2583 2584 1. A copy of mydetails.txt.asc file from Question 2 Question 1: Snort Rules (10 Marks) Scenario A small company has a network set up behind a NAT router. The router is connected to the Internet via a single ISP provided dynamic IP address. The ISP provided access address may change over short periods of time. The internal network is RFC 1918 Category 2 compliant, and uses the private address space 192.168.2.0/24. The gateway router is configured to use DHCP allocated IP addresses to internal hosts as they connect. However, a record is kept within the router of what IP addresses have previously been allocated to specific MAC addresses. Whenever those MAC addressed hosts disconnect from and later reconnect to the network they are reallocated the same IP address. It is only if the router has a power off episode, or is manually reset, that allocation of different IP addresses may occur (and even then, the same addresses may be allocated as before). The company operates an approved internal web server at 192.168.2.21:80, to facilitate in-house development of web pages and web sites that will later be deployed to an external server for public access. It is a company policy that only one approved internal web server is to be in operation on the network. You are the company IT Manager. It has come to your notice that a company employee has set up a rogue web server on the internal network, using a personal laptop. The employee is using that web site to provide undesirable material to a small clique of employees, to whom the web server address has been provided secretly. The company CEO has requested you to: 1. Obtain hard evidence that an employee is in fact using a personal laptop to set up a rogue web server. 2. Find out what other employees are accessing the rogue web site. Considerations  The rogue web server may be on any internal IP address, and will be using any of the ephemeral ports. It will not be using a well-known port.  The clients accessing the rogue web server may come from any internal IP address using any ephemeral port.  The MAC addresses of all company host devices are on record.  The MAC address of the device being used to host the rogue web server, and the MAC addresses of all devices that connect to the rogue server, need to be obtained for later use as evidence. Technical Approach to the Solution To carry out the CEO's request you have decided to: A) Use Wireshark to capture packet data on the internal network. B) Use snort to monitor for any internal network HTTP traffic destined for any internal host on any port address other than the authorised company internal web server and produce an alert message. The snort monitoring will identify when breaches have occurred. The Wireshark pcap file containing the captured packets can be time correlated with the logged snort alerts to obtain MAC addresses for source and target. Your Task You are to write a .conf file containing the snort rule(s) that will accomplish the technical approach to a solution. Hint  For this question, make sure you do the Snort Project - Week 8 (Intrusion Detection Concepts), located in the course Moodle Site. If your rule is correct thealert.ids file will show entries like the following: [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:29.439844 192.168.2.5:49496 -> 192.168.2.2:6400 TCP TTL:64 TOS:0x0 ID:18940 IpLen:20 DgmLen:408 DF ***AP*** Seq: 0xE8349C5 Ack: 0xBCB171EE Win: 0xFFFF TcpLen: 32 TCP Options (3) => NOP NOP TS: 1210791384 0 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:29.440554 192.168.2.2:6400 -> 192.168.2.5:49496 TCP TTL:128 TOS:0x0 ID:1065 IpLen:20 DgmLen:1300 DF ***A**** Seq: 0xBCB171EE Ack: 0xE834B29 Win: 0xFE9B TcpLen: 32 TCP Options (3) => NOP NOP TS: 195453 1210791384 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:29.449929 192.168.2.5:49496 -> 192.168.2.2:6400 TCP TTL:64 TOS:0x0 ID:18942 IpLen:20 DgmLen:367 DF ***AP*** Seq: 0xE834B29 Ack: 0xBCB1799C Win: 0xFFFF TcpLen: 32 TCP Options (3) => NOP NOP TS: 1210791384 195453 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:29.450478 192.168.2.2:6400 -> 192.168.2.5:49496 TCP TTL:128 TOS:0x0 ID:1067 IpLen:20 DgmLen:485 DF ***AP*** Seq: 0xBCB1799C Ack: 0xE834C64 Win: 0xFD60 TcpLen: 32 TCP Options (3) => NOP NOP TS: 195453 1210791384 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:43.904673 192.168.2.5:49496 -> 192.168.2.2:6400 TCP TTL:64 TOS:0x0 ID:18947 IpLen:20 DgmLen:451 DF ***AP*** Seq: 0xE834C64 Ack: 0xBCB17B4E Win: 0xFFFF TcpLen: 32 TCP Options (3) => NOP NOP TS: 1210791413 195509 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:43.913290 192.168.2.5:49497 -> 192.168.2.2:6400 TCP TTL:64 TOS:0x0 ID:18950 IpLen:20 DgmLen:451 DF ***AP*** Seq: 0xBF45540D Ack: 0xBEFA2FE2 Win: 0xFFFF TcpLen: 32 TCP Options (3) => NOP NOP TS: 1210791413 0 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:43.913886 192.168.2.2:6400 -> 192.168.2.5:49497 TCP TTL:128 TOS:0x0 ID:1071 IpLen:20 DgmLen:571 DF ***AP*** Seq: 0xBEFA2FE2 Ack: 0xBF45559C Win: 0xFE70 TcpLen: 32 TCP Options (3) => NOP NOP TS: 195597 1210791413 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:43.919054 192.168.2.5:49498 -> 192.168.2.2:6400 TCP TTL:64 TOS:0x0 ID:18956 IpLen:20 DgmLen:365 DF ***AP*** Seq: 0x18030D8E Ack: 0xCFE60A18 Win: 0xFFFF TcpLen: 32 TCP Options (3) => NOP NOP TS: 1210791413 0 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:10:43.946959 192.168.2.2:6400 -> 192.168.2.5:49498 TCP TTL:128 TOS:0x0 ID:1075 IpLen:20 DgmLen:660 DF ***AP*** Seq: 0xCFE60A18 Ack: 0x18030EC7 Win: 0xFEC6 TcpLen: 32 TCP Options (3) => NOP NOP TS: 195598 1210791413 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:11.614057 192.168.2.3:1923 -> 192.168.2.2:6400 TCP TTL:128 TOS:0x0 ID:44619 IpLen:20 DgmLen:496 DF ***AP*** Seq: 0xC9090643 Ack: 0x550D4778 Win: 0xFFFF TcpLen: 20 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:11.656165 192.168.2.2:6400 -> 192.168.2.3:1923 TCP TTL:128 TOS:0x0 ID:1079 IpLen:20 DgmLen:230 DF ***AP*** Seq: 0x550D4778 Ack: 0xC909080B Win: 0xFE37 TcpLen: 20 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:19.504867 192.168.2.3:1926 -> 192.168.2.2:6400 TCP TTL:128 TOS:0x0 ID:44648 IpLen:20 DgmLen:450 DF ***AP*** Seq: 0xEC018654 Ack: 0x5E762A07 Win: 0xFFFF TcpLen: 20 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:19.540195 192.168.2.2:6400 -> 192.168.2.3:1926 TCP TTL:128 TOS:0x0 ID:1082 IpLen:20 DgmLen:555 DF ***AP*** Seq: 0x5E762A07 Ack: 0xEC0187EE Win: 0xFE65 TcpLen: 20 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:19.550534 192.168.2.3:1926 -> 192.168.2.2:6400 TCP TTL:128 TOS:0x0 ID:44650 IpLen:20 DgmLen:451 DF ***AP*** Seq: 0xEC0187EE Ack: 0x5E762C0A Win: 0xFDFC TcpLen: 20 [**] [1:1000010:1] Unauthorised HTTP traffic [**] [Classification: ] [Priority: 1] 09/12-19:11:19.590606 192.168.2.2:6400 -> 192.168.2.3:1926 TCP TTL:128 TOS:0x0 ID:1083 IpLen:20 DgmLen:792 DF ***AP*** Seq: 0x5E762C0A Ack: 0xEC018989 Win: 0xFCCA TcpLen: 20 Note: The classification identifier has been deleted. Tips: ·Search for the HTTP RFC document “RFC2616” via Google. In particular, you will need to familiarise yourself with the HTTP header contents. You need to identify some text pattern in the HTTP header that will unambiguously indicate whether a client is accessing a web server, or vice versa. (remember, the rogue web server is operating on a non-standard ephemeral port.) ·Certain characters are “special” in SNORT rules. These characters must be escaped to tell SNORT to treat them literally, rather than interpret their special meaning. To escape a special character, you simply precede it with a back-slash “\”. For example, if you wish to continue your rule on a new line in the configuration file, then you end the line with a “\” character to escape the special meaning of the ENTER character at the end of the line. SNORT treats the ENTER character as special. It means it is the end of the current rule. With a “\” at the end of the line, it tells SNORT to treat it as a literal ENTER which will be interpreted as just spacing for your rule and allows it to continue on the next line. If you receive the following error when you attempt to run your rule through SNORT: “ParsePattern Got Null enclosed in quotation marks (")!”, then you have a special character in your rule content that needs to be escaped. Refer to the SNORT documentation website for details on which characters have special meanings. ·Make sure you include the standard Snort classtypes in your rule. Refer to the SNORT documentation to determine which classtype is appropriate for this exploit as described above. You will probably have to make use of theclassification.config file (located in theSnort\etc\ directory) – research how to make reference to this file from your rules file. ·Failure to use the correct syntax in your rule will mean the rule is ineffective. This means you will lose marks on this question. ·Refer to the Snort manual for assistance in writing the rules – a link to the manual is availed from the Software Resources section of the course web site. Note: Duplicating the contents from the text, lecture slides, weekly notes or the Internet is not acceptable (even if it is referenced) and will not attract any marks. Your solutions must be written in your own words. If you cannot write your answer in your own words, then you have not yet mastered the topic and require further reading or advice from your tutor. Any information taken from an external source (either from the textbook or any other source) must be referenced appropriately. Failure to do so constitutes plagiarism. 1.1. Identification of Addresses By inspecting the sample alert.ids entries given above you should be able to identify: 1. The IP address, and port number of the device hosting the rogue web server. 2. The IP addresses of all devices that access the rogue web server. You are to enter this information into a table (see following), and submit it with your assignment submission document. Description IP Address Rogue Web Server Accessing Client #1 Accessing Client #2 Explain in your own words how the MAC addresses of these devices can be discovered from the pcap file. Question 1.1 Marking Criteria Port Number Up to a maximum of 4 marks for correctly identifying the rogue web server and the accessing clients’ information (table above)). 1 mark for explanation of MAC address identification. 1.2. For the SNORT Rule: 2.5 marks for commenting, and 2.5 marks for rule correctness using table below Line Number SNORT RULE 1 2 3 4 5 6 7 8 9 10 Question 2 10 marks You are the Chief Information security Officer (CISO) of a small medium sized - accounting Services Company. In the last few weeks, senior staff have been complaining that some confidential information has been disclosed via email without any authorisation. You are approached by the Chief Information Officer (CIO) to discuss the issue and see the most appropriate way to tackle this problem. You suspect that some of the employees might be using their technical skills to access sensitive information either from the mail servers or during transmission. To counteract this malpractice, you suggest the CIO the implementation of encryption. Before you actually implement the system, you want to conduct a pilot using the GNU Privacy Guard (GPG) software. The pilot requires that you install GNU Privacy Guard (GPG) software onto your own computer and complete the following activities. Note: The GNU Privacy Guard is available for free download from http://www.gnupg.org/ and “A Practical Introduction to GNU Privacy Guard in Windows” by Brendan Kidwell is available at http://www.glump.net/howto/gpg_intro After installing GPG software onto your own computer, complete the following tasks: 1. Generate your own key-pair by using GPG software and do not create a pass-phrase for your private key (in a real world this is not a good practice. Just for the sake of this assignment, do not create a pass-phrase). You need to use screen-shots to show that you have successfully completed this task. A valid screen-shot is similar to the one shown in Figure 1. Pay attention to the red circles, which demonstrate the success of key pair generation ( 2 marks). Figure 1Key Pair Creation 2. Export your public key and paste it into your assignment document. You need to use two screen-shots to show that you have successfully completed this task. One screen-shot is to show the use of gpg command and the other is to show the exported public key. For example, the screen-shot in Figure 2, shows a public key, which is exported into the file: CC-pubkey.txt (2 marks). Figure 2Screen-shot of a Public Key 3. Explain the steps how to import your Lecturer’s public key from the key-serverhttp://pgp.mit.edu (your lecturer created a public key and stored it at the MIT PGP Public Key Server). Include in the assignment document the gpg command line, individual options you used and their meaning. As above, use screenshots of website interactions, with accompanying explanations of the screenshots to explain the steps how to import your Lecturer’s public key from the keyserverhttp://pgp.mit.edu(3 marks). 4. Create an ASCII text file to store your full-name, your student number, and your student CQU email address (please do not use any other email address). Then using your lecturer’s public key, encrypt this text file. The resulting file should also be ASCII armored so that it is readable once decrypted by your lecturer / tutor. Failure to do so will result in loss of marks. Submit the resulting encrypted file along with your assignment solutions document (word document) via the online submission system and following the naming convention given above (3 marks). An example explaining the steps to export a key Here is a specific example for explaining the step of exporting a private key, to be imported onto another computer running GPG. Use this example to guide you in how to give explanations in this question. To export your private key, you need to execute the following gpg command: gpg --output “privkey.txt” --export-secret-keys “Xiao Li” The outputoption specifies the filename in which to write the private key into. Finally, the export-secret-keys option specifies the name of the private key to be exported. The name is given as “Xiao Li”. This option is distinct from the “export” option which exports only public keys. Now the private key is stored in the file “privkey.txt” unencrypted and can be imported into another version of GPG. Hints: Where required be detailed and specific about your actions explaining exactly what you did, and why you did not. Document the exact GPG commands you have used, and provide an explanation of what the command does, including the individual command line options, and/or provide screenshots of any interactions with websites. Brendan Kidwell’s practical guide is not the only one available on the Internet. There are plenty of other documents on the Internet that explain how to use GPG for various functions. Marking: 2 Marks for key-pair creation 2 Marks for exporting your public key 3 Marks forexplaining the steps how to import your Lecturer’s public key from the key-server 3 Marks forcreating an ASCII text file and encrypting it using your lecturer’s public key Attach 2584 2585 i want you to do summarize for this work. take a look to the reading summary 230 and do the work that is asking for in chapter 2 Attach 2586 2586 Issues of supply chain management in E-commerce -an issue paper with academic references 2587 Write a C program that treats A1A0, A3A2, and A5A4 as three 2-bit unsigned binary number. The program should output the sum of those three numbers onto B. 2588  Suppose an executive-level manager asked you to explain the importance of encryption. Detail the key points that you would use to justify the importance of using encryption during the overall security posture analysis of the executive-level manager’s organization. Describe at least two (2) uses of encryption within organizations today that you found in your research. From the uses identified, indicate the information resource the encryption is designed to protect. Assess the importance of protecting such an information resource from a security perspective. 2589 what is private network? 2590 8.1 Describe the IBM 5360/370 channel ISA in terms of data types, addresses, and operations. 8.2 What instruction could be used with the IBM S360 to determine if the condition code permits access to a datum that is protected with a semaphore? 2591 Consult the Intel Pentium Pro documentation on performance monitoring and determine how the miss rate of the instruction cache and the data cache can be determined. 2592 The paper "PicoJava: A Direct Execution Engine for Java Bytecode" by McGhan and O'Connor, found inComputer, October 1998, describes a processor for ex ecuting Java programs. Write an essay describing the salient architecture and im plementation features of this processor in 500 words or less. 2593 3. Describe the meaning of the circled numbers 1, 2, and 3, of Figure 8.6. 3. Section 4.6 describes four segment/page configurations that are used with the IBM 5370. For each of these configurations, Iist the number of bits that are added in the two adders and the bits concatenated in the real-address register of Figure 8.6. Recall that the 5370 has a 24-bit effective or logical address. 2594 3. What is the length of the virtual address of the Pentium Pro? 3. Figure 8.8 shows the Pentium Pro segmented virtual-address system for 4K-byte pages. The system can also support 1M-byte pages. Show how the linear address and tables are reconfigured for 1 M-byte pages. 2593 Explain why two adders are used for the 5370 virtual-address translation, Figure 8.6, whereas only one adder is used for the Pentium Pro, Figure 8.8. 2594 Consider the synchronization instructions discussed in Section 8.6. What happens when two or more requests to access the semaphore arrive on exactly the same clock? 2595 3. Derive the model for MIOPS used in the example in Section 8.7. 8.1 2 What is done with the two 32-bit results computed in the multiply and add in struction shown in Figure 8.19? In other words, how can these results be used as inputs to subsequent instructions? Note that the source operands are 16 bits. 2596 Using the example above on WWW response time, will the result be signifi cantly different if the estimate of 1 s for the service time is changed to 0.1 s? Work out the solution. 2597 Write a program using the van Neumann ISA, Table 1.2, for maintaining a counter in a memory location to control a programmed 1/0 transfer. 2598 Derive a model for the percentage of increase in the time in the queue that is a function of an increase in pfrom p 1 to p 2 • Assume that µ, does not change. Verify your solution with the example found with the airport departure runway example. 2599 A computer's bus is 0.5 m long and the card holding the clock generator is placed in the center of the bus. What deskewing delay, in nanoseconds, is required on the clock feeding the logic on this center board? You must make an assumption as to the propagation delay down the bus for terminated lines. 2600 5. For the example on terminals, in Subsection 7.6.2, recompute the server speedup needed for t 1 = 1 rather than t 1 = 2. 5. 2601 Consult the documentation for the Intel 8080 and list the complete set of codes for the three pins noted in Section 7.1. Refer to Figure 7.13 in which deskewing delays are inserted in the clock lines. What is the magnitude of the delay for each card slot under the assumption that there can be five cards on the bus? 2602 8. Why is distribution of a skew-free clock over a serial transmission path impracti cal? This issue is discussed in Section 7.4. 8. You are shown the plot of Figure 7.25. The distribution seems to be Poisson. From these data compute the value of J.... 2603 10. Find the server speedup required in the last example on example in Subsection 7.6.2 if think time decreases to 1 s when the mean response time is decreased to 0.5 s. 10. The programmed 1/0 example assumed a processor with a 0.1-MIPS instruction processing rate. Rework this example with MIPS = 0.1, 1, 10, and 100. Plot your results of efficiency versus MIPS. 2604 7.12 The example in Section 7.2 shows the system providing 12.35 transactions per second. Assume a requirement of 500 transactions per second. The processor will be unchanged but additional disks will be added. How many disks are required? 2605 6.16 You are redesigning the BTB of a processor and can increase the number of bits by 50%. How would you spend these additional bits? Increase the number of entries, thereby decreasing the miss rate? Increase the size of the history table to improve the accuracy of prediction? Any other ideas? Justify your answer based on the reduction in WABD. 2606 6.1 7 Rework the WABD model for the BTB, Table 6.7. Change the default case when there is a BTB miss to be predict take and predict not take. 6.18 Rework the example in the Section on BTBs by using the PT and PNT Strategies as default. Which default strategy would you use for this design? Explain your answer. 2607 6.1 9 Examine the weighted average number of register file accesses per clock by pass ing the following instruction stream down the base pipeline: a = 1. The instruc tion stream is load, ALU, load, other, ALU, other, other, other, ALU, store. Com pute the fraction of instructions having 0, 1, 2, and 3 register file references. How do these results compare with the result of Table 6.3 and the reported simulation? 2608 8. Show by the use of reservation tables that the forwarding delay is E - 1 clocks for adjacent instructions. 8. Describe a situation in which the write to register stage of the pipeline can cause an interrupt and be the interrupting stage. 10. Show the derivation of the model for the number or clocks, s + [( k - 1)/a], for a degree 2 superscalar processor with the probabi Iity of alignment 1 /a . 10. What conditions or situations could result in no instructions being issued from the window of Figure 6.19? 2609 2610 12. i Rx = M(R y) For the superscalar processor of Figure 6.19, consider the two-instruction se quence: load floating point, add floating point j Rz = Rx + Rw. Show a forwarding path that will improve the performance of this program frag ment. Explain how performance is improved. 2611 6.1 3 Identify all forwarding paths on the superscalar processor of Figure 6.19 that will improve performance loss that is due to RAW dependencies. 6.14 The base pipeline has s" = 2, s' = s = 3. Compute the CPI for the three branch strategies, freeze, predict take, and predict not take. The workload parameters are Pb = 0.4 and Pbt = 0.6. 2612 6.1 5 Rework the example in Subsection 6.3.2 to include cache misses. The one-level unifi ed cache is organized direct with 8K bytes. With the split cache, the instruc tion and data caches are direct with 4K bytes. Use Pmiss data from Tables 4.8-4.10. The real memory to the unifi ed cache transport time is 10 clocks. See Figure 4.10 for the topologies of the one-level unifi ed cache and the one-level split cache. 2613 6.20 Split caches, instruction and data, remove the structural hazard from memory references. Discuss the requirements for maintaining coherency between these two caches. 2614 1. For the example hardwired design, write the input equations using T and JK flip flops. 2. For hardwired control, assume that the increment PC states can be subsumed by the instruction fetch states and that the target address state is subsumed by the EA execute state if the clock is lengthened by 10%: 1. Draw the state transition flow-chart. 2. Derive the input equations for JK flip flops. 3. What is the speedup of this implementation over the eight state implementation? 2615 Explain why a hardwired control unit was used with the fastest model of the IBM 5360 whereas microprogrammed control was used with the lower- performance models. 2616 An alternative way to design a hardwired state machine is to use one flip flop per state rather than encoding the states as shown in the example. Using T flip flops, write the input equations for this design technique. 2617 Consult the library and find evidence that the number of bits of a micropro gram for a given ISA is approximately equal regardless of the speed of the pro cessor. There is available information on the IBM 5360 and DEC VAX. You must look. 2618 6. Write the microprogram for the macroload instruction. 6. Because most macroinstructions require several microinstructions for executing, what happens to the microprocessor if there is an external interrupt in the middle of the instruction execution? Are there design alternatives? 2619 Some microprogrammed control units have the ability to call microsubroutines. What changes must be made to Figure 5.9 to provide this facility? Recall the discussion on the necessary facilities for subroutines in Chapters 1 and 3. 2620 From the state diagram of Figure 5.1, determine the internal register organization (accumulator, register file, stack, etc.) of the processor. 2621 10. Table 5.3 shows the state transition truth table for the state diagram of Figure 5.6. Instead of encoding the states with five flip flops, use one JK flip flop per state (23 flip flops). Write the J and K input equations for this control state machine. 2622 11. Complete the logic equations for the b, c, d, and e flip flops for the State transition truth table of Table 5.2. 5.1 2 For the micro ISA, what are the operations, data types, and addresses? 5.1 3 Show how the microprogram of Figure 5.10 can be rewritten to use a common body of code for incrementing the program counter. 2623 5.1 4 Design the state machine for the control of the van Neumann ISA described in Chapter 1. 5.1 5 Explain how one would design a microprogrammed processor without a macro program counter or a microprogram counters by using linked lists. 2624 5.1 6 Is the micro control unit of Figure 5.9 a Harvard or a van Neumann architecture? Explain your answer. 5.1 7 Can the micro control unit of Figure 5.9 execute subroutines? Explain your answer. 2625 4.1 There are two write hit and two write miss policies, giving four possible designs. List these four designs and discuss the feasibility of each. 2. An instruction cache is large enough to hold a loop. What is the instruction cache Pmiss for a loop that is executed 50,100, and 200 times? 2626 Derive a model for the effective cache latency of Figure 4.24. Take the first deriva tive, set to zero, and solve for the minimum. 2627 Comment on the performance of an interleaved memory if the degree of inter leaving is a prime number: 3, 5, 7 etc., rather than an even power of 2. 2628 4. Discuss the problem of synonyms or aliases that are characteristics of virtual address caches. 4. The issue of increasing the size of a pipelined real-address cache has been dis cussed. Using the data on the data miss rate for the SPEC benchmarks, determine the change in Pmiss of the i486 cache for the degree of associativity: 1, 2, 4, and 8. 2629 Refer to the discussion on zoned disks on disks in Section 4.7. Discuss the issue of transfer rates for the two techniques of assigning sectors to tracks. 2630 4.8 Discuss the problems associated with a branch-and-link instruction that places the link in memory if the memory system has a cache. 4.9 Modify the tetrm model found on model derived in Table 4.4 to comprehend a TLB. 2631 4.1 0 Explain why a valid bit is needed to detect a cache hit. Why isn't a tag comparison sufficient? 4.11 The figures showing direct and inverted page tables do not show valid bits. Are valid bits needed? Explain your answer. 2632 4.1 2 Figure 4.26 shows the 5370 address translation path. Assume the following. Ac cessing the segment table and the page table in real memory takes four memory cycles each. Accessing the TLB takes 0.1 memory cycles. The TLB has a hit rate of 0.95. What is the effective address translation time for the 5370? 2633 4.13 Figure 4.33 shows that the Intel Pentium Pro TLB uses as its input the virtual or the linear address. How does this architecture overcome the delay of accessing the descriptor table? 2634 4.1 4 Explain how the Intel page directory table is indexed with 30 bits if the real mem ory address is 32 bits. 4.1 5 Rework the example on the weighted average number of probes for the inverted student class file on file of Table 4.8 and Figure 4.8. Use two hashing schemes: the hash is the three least-significant digits and the hash is the one least-significant digit. Recall that, when the two least-significant digits are used, the weighted av erage number of probes is 1.32. 2635 4.16 Compute and plot the effective cache latency for bus widths of 1, 2, 4, 8, 16, and 32 bytes by using the parameters of the example on page 167. Use a 64 byte block. 4.1 7 Table 4.8 shows Pmiss for instruction caches and Table 4.9 shows Pmiss for data caches. Is it possible to construct a reasonable estimate of the data in Table 4.10 by using the data from Tables 4.8 and 4.9? If so, construct the table; if not, explain why not. 2636 4.1 8 The text mentions that a five-way set associative cache can be designed. Explain the advantages and the disadvantages of this design. Is a prime-number-way in terleaving advantageous or disadvantageous? 2637 19. Construct the event table, similar to Table 4.13, for a data write. 19. Assign miss rates and action times for Table 4.13 and compute a weighted average memory write time. 19. Redraw Figures 4.12 and 4.13 to reflect the modern cache designs that have one block slot per sector. 2638 3.1 3 The Year 2000 problem is with us because the two LSD digits of the year are encoded, in BCD, i nto a single byte. As you shou ld know, there are u nused states i n this encoding. Design a 1-byte encodi ng that wi l l i nd icate the year withi n the twentieth and the twenty-first centu ries. 8 bits can encode 256 states, so encod ing 200 states shou ld pose no problem. 2639 3.1 4 The text states that the exponent bias of the I BM 5360 floating-poi nt format is 64. What is the bi nary val ue of the exponent and what is the val ue of the exponent? 2640 The exponent bias for the I BM 5360 is 2n-l whereas that of the I EEE format is 2n-l - 1, where n is the number of exponent bits. Explai n why these biases differ and cite the advantages and disadvantages of each. 2641 15. For the I BM 5360 op-codes, what are the bind ings, i n the four LSBs, of the floati ng poi nt and the fixed-poi nt data types to the operations? 3.1 7 Explain why a hidden bit can be used only with a floating-poi nt format of base 2. 2642 18. Descri be I EEE rou nd to nearest if appl ied to the I BM 5360 floating-poi nt data type. 18. Assume that the fractional part of an IEEE floating-poi nt significand is 4 bits and that there is a rou nd and sticky bit. Start with 0.0100, 00 and increment the sticky bit up to 0.1011, 11. Use the rou nd ing ru les of Table 3.6; plot the rou nded values of the 4-bit significand along with the i nfin ite precise values (6 bits) for each of the i nfinitely precise values. 2643 18. The Atanasoff Berry Computer,described in Chapter 1 , uses Gaussian elimination to solve linear algebraic equations; see Figure 1.9. Show how the ABC solves for x and y by using binary data types; 3 x + 2 y = 12, 4x + y = 11. 2644 Can the two steps of the x86 decimal-adjust operation be combined into one step? If so, describe the operation. If not, explain why not. 2645 2646 18. The text states in Section 3.3 that one advantage of a fixed-length instruction is that instructions will not cross page boundaries. Explain why this is so. 18. Consult Intel documentation on any member of the x86 family and explain how signed decimal arithmetic is performed. The combinations of fixed-length/variable-length instructions and op-codes are discussed in Subsection 3.2.4. Why is the combination of fixed-length instruc tions and op-codes not included in the list of design options? 2647 2648 18. The program counter of the VAX is allocated to register 15 of the register file. Discuss the advantages and disadvantages of this design. 18. Consult the documentation for the IBM 5390 and construct the equivalent ofTable 10. IBM 5360 op-code classes. The example in Subsection 3.2.3 shows that base 16 requires 2 fewer bits than base 2 for the same range. The equality was solved by assuming one base 16 ex ponent bit. Show another solution of the equality that makes no such assumption and shows that the result is general. 2649 18. The average length of an 8086 instruction was given as 2.25 bytes in Section 3.3. This average was found by running programs in 1989. At this time, do you think the number of bytes per Pentium Pro instructions is less than or greater than 2.25? Explain your answer and give an estimate that you would use for modeling purposes. 2650 Provide a rationale for the round-to-nearest-domain function of the IEEE floating-point standard for the case in which R = 1 and S = 0. 2651 Figure 3.9 shows three classes of interrupt handling methods. However, the text suggests that there are four: the combinations of between instructions or within and instruction and continuation and restart. Explain how these four methods are accomodated in Figure 3.9. 2652 18. Generalize the rules for making the correction to biased exponents after an addi tion or subtraction. 18. Are the Intel integer data types one of the six data types described in Table 3.6? Explain your answer. 2653 Redo the example of biased exponents in Subsection 3.5.3 by using a bias of 4 rather than 3. Discuss the advantage of this change. 2654 2. From Table 3.12, determine the bias for each of the floating-poi nt formats listed. Assume that the biases are even powers of 2. 2. Consult Intel documentation and show how the Intel Pentium with MMX uses expanded op-codes. 2655 What is the range, in bytes, of the length of Pentium Pro instructions? That is, how long are the shortest and the longest instructions? 2656 Assume the following: 40% of all executed branches instructions are uncondi tional branches and 76% of all branches are taken. What percentage of all exe cuted branches are taken conditional branches? 2657 You are designing an ISA and need to allocate bits in the instruction for immedi ate operands. An examination of 399 immediate operands shows the following distribution: Address Bits Total Number Fraction 41 0.103 2 89 0.223 3 47 0.118 4 90 0.226 5 46 0.115 6 57 0.143 7 18 0.045 8 4 O.ol O 9 5 0.012 10 2 0.005 Total 399 1.00 You have decided that you can have one of two designs: Design a: a 4-bit short immed iate and a 10-bit long immediate. Design b: a 8-bit short immed iate and a 10-bit long immediate. Which of these two designs wi ll give the smallest weighted average number of bits for immediate val ues? 2658 3.7 Derive the ru les for the x86 decimal adjust for subtraction instruction. 3.8 You are design ing an excess data type that wi ll represent 0-99 i n an 8-bit byte. What is the excess val ue? 2659 3.9 Show the 10 decimal d igits for a 4-bit code havi ng the weights +6, +2, -2, +1. 10. I n the d iscussion of the I BM 5360 floating-poi nt format, the followi ng statement is made: If the 16 states of the hex field are evenly distributed, there is approx imately a 3/4 wasted bit i n the fraction. For worst case, 3 bits are wasted i n the fraction. Explai n and justify this statement. 2660 10. Using Swenney's data, Table 3.9, what is the weighted average nu mber of shifts req uired for normal ization with a base 2 floatingpoi nt data type? 3.1 2 The x86 ISA provides for a BCD data type. Is this not redu ndant with the decimal adjust instruction? Explain you r answer. 2661 1 .1 Write the program for vector addition by using the ISAs of the IBM Power PC and the Intel Pentium. 1 .2 Rewrite the von Neumann ISA vector add program for vectors of length 300. 2662 1 .3 ls there a reason why the vector add program is written so that the vectors are added starting with the large address working back to the small address? 1 .4 Babbage was interested in the solution to the expression n2 +n+41 for increasing integer values of n. Show how this problem is solved on the difference engine for n = 1, 2, . . . , 10. 2663 1 .5 Obtain the first terms of sin by using a well-known series expansion. Then com pute the first 10 terms of the sin function by using the methods of differences. 1 .6 Use the ENIAC and the format of Table 1.6 to compute n, n2 , and n 3 for n = 1, n = 2, and n = 3. 1.7 Expand the program of Table 1.6 to compute n 4 with the ENIAC. Hint: 2664 ( n+ 1) 4 = ( n+ 1)(n + 1)(n + 1)(n + 1). 1 .8 Write a program to evaluate a 3 x 3 determinant for the Z3. Assume that the nine inputs are keyed in by means of the keyboard. 2665 1.9 Show the method by which the ABC solves the following simultaneous equations. Use decimal values and plot the convergence of the first coefficient to zero: 2 x + S y = 9, 3x + 2 y = 8. 2666 10. Compare the characteristics of each of the four machines described in Table 1.7 with modern machines or current research. 10. Figure 1.10 shows a rotating drum with brushes used to make conversions be tween base 10 and base 2. Suggest how this device performs this function. 2667 1 .12 Show the execution steps for Instructions 1 and 3 in Table 1.2 in the flow-chart form used in Figure 1.7. 2668 9. Explain the origin of the names arithmetic mean, harmonic mean, and geometric mean. 9. One of the most frequently used applications of the geometric mean is to cal culate compound growth rate. Derive the compound growth formula, given in Section 2 .1, from the geometric mean. 2669 1. Go to a library and check your local newspapers. Find the advertised prices for disks and DRAMs used in PCs. The prices are user prices and are usually found in the business sections. Tabulate these prices for the past five years (old newspapers will be found on microfi Im) and compute the learning curve factor, assuming that volume doubled every year. Make sure that you adjust for inflation. 2670 The performance improvements (in time reduction) in the latest version of seven layers of a new networking protocol were measured separately for each layer, as shown in Table 2.7. What is the mean or average improvement per layer? What is the overall speedup of the protocol? 2671 Two benchmarks are run on a computer. BM 1 executes at 10 MIPS, and BM 2 executes at 15 MIPS. What single number should be used to represent the perfor mance of this processor? 2672 2.4 Three computers execute two benchmarks in the times shown in Table 2.8 (Smith 1988). Answer the following questions, showing the calculations: A is x % faster than B for BM 1. A is x % faster than C for BM 1. B is x % faster than C for BM 1. B is x % faster than Afor BM 2. C is x% faster than A for BM 2. C is x % faster than B for BM 2. B is x% faster than A for the two benchmarks. C is x% faster than B for the two benchmarks. C is x% faster than A for the two benchmarks. 2673 5. An enhanced computer system executes two programs in 40 s with 80% of the time devoted to the nonenhanced program. When the two programs are BM ComputerA ComputerB ComputerC 1 (s) 1 10 20 2 (s) 1000 100 20 TOTAL TIME (s) 1001 110 40 executed on the nonenhanced system, the execution time is 200 s. What is the speedup of the enhanced portion? 2674 Your company is able to produce twice as many of a product each year as during the year before. At what rate is the cumulative volume of this product increasing per year? Explain your answer. 2675 Two microprocessors have been designed. One processor has an initial manu facturing cost of $1000 and the other has an initial manufacturing cost of $512. The learning curve for both processors is 0.80. What is the ratio of the cumulative volume of the two processors at which their manufacturing costs are equal? 2676 7. A formula for determining the MIPS of a processor is clock frequency MlPS = . CPI x 10 6 Derive this formula from task time = number of instructions executed x CPI x time per clock. 2677 1. Find the least common multiple of the following polynomials over F 2 : f 1( x ) = 1 + x 2, f 2( x ) = 1 + x + x 2+ x 4, f 3( x ) = 1 + x 2+ x 4+ x 6. 2. Suppose we have three nonzero polynomials f 1 ( x ) , f 2 ( x ) and f 3 ( x ). Show that lcm( f 1 ( x ) , f 2 ( x ) , f 3 ( x )) = lcm(lcm( f 1 ( x ) , f 2 ( x )) , f 3 ( x )). 2678 Construct a generator polynomial and a parity-check matrix for a binary double-error-correcting BCH code of length 15. 2579 4. Let α be a root of 1 + x + x 4 ∈ F 2 [ x ]. Show that α 7 is a primitive element of F 16 , and find the minimal 1. polynomial of α 7 with respect to F 2 . Let g ( x ) ∈ F 2 [ x ] be the polynomial of lowest degree such that g ( α 7 i ) = 0, for i = 1 , 2 , 3 , 4. Determine g ( x) and 2. construct a parity-check matrix of the binary cyclic code generated by g ( x ). 2680 5. Determine the generator polynomials of all binary BCH codes of length 31 with designed distance 5. 5. Construct the generator polynomial for a self-orthogonal binary BCH code of length 31 and dimension 15. 2681 7.Let α be a root of 1 + x + x 4 ∈ F 2 [ x ]. Let C be the narrow-sense binary BCH code of length 15 with designed distance 5. 1. Find the generator polynomial of C . 2. If possible, determine the error positions of the following received words: (i) w ( x ) = 1 + x 6 + x 7 + x 8 ; (ii) w ( x ) = 1 + x + x 4 + x 5 + x 6 + x 9 ; (iii) w ( x ) = 1 + x + x 7 . 2682 8. Let α be a root of 1 + x + x 4 ∈ F 2 [ x ]. Let C be the narrow-sense binary BCH code of length 15 with designed distance 7. 1. Show that C is generated by g ( x ) = 1 + x + x 2 + x 4 + x 5 + x 8 + x 10 . 2. Let w ( x ) = 1 + x + x 6 + x 7 + x 8 be a received word. Find the syndrome polynomial, the error locator polynomial and decode the word w ( x ). 2683 9.Let C be a narrow-sense q -ary BCH code of length n = q m − 1 with designed distance δ generated by g ( x ) := lcm( M (1) ( x ) , M (2) ( x ) ,..., M ( δ − 1) ( x )), where M ( i ) ( x ) is the minimal polynomial of α i with respect to F q for a primitive element α of F q m . Put   1 α ( α ) 2 ··· ( α ) n − 1  1 α 2 ( α 2 ) 2 ··· ( α 2 ) n − 1    1 α 3 ( α 3 ) 2 ··· ( α 3 ) n − 1    H=···· .   ·······     1α ···· δ −1 ( α δ −1 ) 2 ··· ( α δ −1 ) n −1 Define the syndrome S H ( w ) ofa word w ∈ F n with respect to H by w H T . q Show that, for any two words , v ∈ F n , we have 1. SH (u+v)=SH (u)+SH uq ( v ); S H ( u ) = 0 if and only if u ∈ C ; 2. 2. 2684 S H ( u ) = S H ( v ) if and only if u and v are in the same coset of C . Show that the minimum distance of a narrow-sense binary BCH code is always odd. 2685 11. Show that a narrow-sense binary BCH code of length n = 2 m − 1 and designed distance 2 t + 1 has minimum distance 2 t + 1, provided that t+11 2 m −1 i =0 i > 2 mt . 2686 Show that the narrow-sense binary BCH codes of length 31 and designed distance δ = 3 , 5 , 7 have minimum distance 3 , 5 , 7, respectively. 2687 Show that the minimum distance of a q -ary BCH code of length n and designed distance δ is equal to δ , provided that n is divisible by δ . 2688 14. (i) Show that the cyclotomic cosets C 1 , C 3 , C 5 ,..., C 2 t + 1 of 2 modulo 2 m −1 are pairwise distinct and that each contains exactly m elements, provided 2 t + 1 2 Lm/2J+ 1 . (ii) Show that a narrow-sense binary BCH code of length n = 2 m − 1 with designed distance 2 t + 1 has dimension n −mt if 2 t + 1 2 Lm/2J+ 1 . 2689 15. Determine whether the dual of an arbitrary BCH code is a BCH code. 15. Find a generator matrix of a [10, 6]-RS code over F 11 and determine the minimum distance. 2690 17. Determine the generator polynomial of a 16-ary RS code of dimension 10 and find a parity-check matrix. 17. Show that, for all n ≤ q and 1 ≤ k ≤ n , there exists an [ n , k ]-MDS code over F q . 2691 19. Show that the dual of an RS code is again an RS code. 19. Determine the generator polynomials of all the 16-ary self-orthogonal RS codes. 2692 21. Let α be a root of 1 + x + x 2 ∈ F 2 [ x ]. Consider the map φ : F 2 2 → F 2 , a 0 + a 1 α i→ ( a 0 , a 1 ) . 2 Let C bea [3 , 2]-RS code over F 4 . Determine the parameters of φ ∗ ( C ). 2693 22. Let C be a q -ary RS code generated by g ( x ) = n δ − 1 ( x − α i ) with i =1 3 ≤ δ ≤ q − 2, where α is a primitive element of F q . Show that the extended code C is equivalent to a cyclic code if and only if q is a prime. 2694 25. For the following primes p , l and elements α , determine the polynomials g Q ( x ) and g N ( x ) over F l as defined in Definition 8.3.8. 1. p = 7, l = 2 and α is a root of 1 + x 2 + x 3 ∈ F 2 [ x ]. 2. p = 17, l = 2 and α is a root of 1 + x 2 + x 3 + x 4 + x 8 ∈ F 2 [ x ]. 3. p = 13, l = 3 and α is a root of 2 + x 2 + x 3 ∈ F 3 [ x ]. 2695 26. Determine the parameters of the QR codes generated by g Q ( x ) ( g N ( x ), respectively) of Exercise 8.25. Problems 8.27–8.31 are designed to determine the square root bound on the minimum distance of binary QR codes. 2696 27. Let p be a prime of the form 8 m ± 1. Define E Q ( x ) := 1 i∈Np + x i if p is of the form 8 m − 1 i ∈ N px i if p is of the form 8 m + 1 . 1. Show that θ in Definition 8.3.8 can be chosen properly so that E Q ( x ) is an idempotent of the binary QR codeC Q of length p . 2. Put E Q ( x ) = p − 1 e i x i and define the p × p circulant matrix over i =0 F 2:  e 0 e 1 ··· e p − 1  e p −1 e 0 ··· e p −2  G 1=   .  . .. ···   e 1 e 2 ··· e 0 Show that every codeword of the binary QR code C Q of length p is a linear combination of the rows of the matrix 11 G := . G 1 2697 28. Let u i ∈ F p be the multiplicative inverse of i ∈ F ∗ . Show that, for any codeword c ( x ) = p − 1 c i x i of even weight in the binary QR code C Q of length p , the word p − 1 c i x − u i belongs to C Q . (Hint: Show that c ( x ) is p ··· ··· i1 i =0 = a linear combination of the rows of G 1 , and then prove that the statement is true if c ( x ) isa row of G 1 .) 2698 1. Let p be a prime of the form 4 k − 1. 1.Show that −1 is a quadratic nonresidue modulo p . Show that the minimum distance d of the binary [ p , ( p + 1) / 2]-QR codes C Q , C N satisfies d 2 − d + 1 ≥ p . 2. ˜ ˜ 2699 Let g Q ( x ) and g N ( x ) be the two polynomials defined in Definition 8.3.8. The binary codes C Q and C N generated by ( x −1) g Q ( x ) and 2700 (xi + x i ) = 0}. 2. Show that the dual code of a cyclic code is cyclic. 2. Show that the set I ={ f ( x ) ∈ F q [ x ] : f (0) = f (1) = 0} is an ideal of F q [ x ] and find a generator. 2701 Suppose that x , y are two independent variables. Show that the polyno- mial ring F q [ x , y ] is not a principal ideal ring. 2702 Find all the possible monic generators for each of the following ideals: 1. I = 1 + x + x 3 > ⊂ F 2 [ x ] / ( x 7 − 1); (b) I = 1 + x 2 > ⊂ F 3 [ x ] / ( x 4 − 1). 2703 Determine whether the following polynomials are generator polynomials of cyclic codes of given lengths: 1. g ( x ) = 1 + x + x 2 + x 3 + x 4 for a binary cyclic code of length 7; 2. g ( x ) = 2 + 2 x 2 + x 3 for a ternary cyclic code of length 8; 3. g ( x ) = 2 + 2 x + x 3 for a ternary cyclic code of length 13. 2704 7. For each of the following cyclic codes, find the corresponding generator polynomial: (a) { λ (1 , 1 ,..., 1) : λ ∈ F q }⊂ F n ; q (b) {0000 , 1010 , 0101 , 1111}⊂ F 4 2 : ; n −1 (c) {( x 0 , x 1 ,..., x n 1 ) ∈ F n −q i=0 x i = 0}; (d) {( x 0 , x 1 ,..., x n 1 ) ∈ F n : n −1 x 3 = 0}. i =0 i −2 2705 Determine the smallest length for a binary cyclic code for which each of the following polynomials is the generator polynomial: (a) g ( x ) = 1 + x 4 + x 5 ; (b) g ( x ) = 1 + x + x 2 + x 4 + x 6 . 2706 8. Based on Example 3.4.13(ii), determine the following: 1. the number of binary cyclic codes of length 21; 2. all values k for which there exists a binary [21 , k ]-cyclic code; 3. the number of binary [21 , 12]-cyclic codes; 4. the generator polynomial for each of the binary [21 , 12]-cyclic codes. 2707 Based on Example 3.4.13(i), determine the following: 2708 1. the number of ternary cyclic codes of length 13; 2. all values k for which there exists a ternary [13 , k ]-cyclic code; 3. the number of ternary [13 , 7]-cyclic codes; 4. the generator polynomial for each of the ternary [13 , 7]-cyclic codes. Construct the generator polynomials of all binary cyclic codes of length 15. 2709 11. Let g ( x ) = (1 + x )(1 + x + x 3 ) ∈ F 2 [ x ] be the generator polynomial of a binary [7 , 3]-cyclic code C . Write down a generator matrix and a parity-check matrix for C . Construct a generator matrix of the form ( I 3 | A ). 2710 12. Let g ( x ) = 1 + x 4 + x 6 + x 7 + x 8 ∈ F 2 [ x ] be the generator polynomial of a binary [15 , 7]-cyclic code C . Write down a generator matrix and a parity-check matrix for C . Construct a generator matrix of the form ( I 7 | A ). 2711 13. Suppose a generator (or parity-check, respectively) matrix of a linear code C has the property that the cyclic shift of every row is still a codeword (or a codeword in the dual code, respectively). Show that C is a cyclic code. 2712 Let g 1 ( x ) , g 2 ( x ) be the generator polynomials of the q -ary cyclic codes C 1 , C 2 of the same length, respectively. Show that C 1 ⊆ C 2 if and only if g 1 ( x ) is divisible by g 2 ( x ). 2713 15. Let v ∈ F n . Show that the generator polynomial of the smallest cyclic q code containing v is equal to gcd( v ( x ) , x n − 1), where v ( x ) is the poly- nomial corresponding to v . 2714 16. Determine the generator polynomial and the dimension of the smallest cyclic code containing each of the following words, respectively: (a) 1000111 ∈ F 7 ; 2 (b) (1 0 , 2 , 0 , 2 , 0 , 1 , 1) ∈ F 8 , (c) 101010111110010 ∈ 2 . 3 ; F 15 2715 17. Let g ( x ) be the generator polynomial of a q -ary cyclic code C of length n . Put h ( x ) = ( x n − 1) / g ( x ). Show that, if a ( x ) is a polynomial satisfying gcd( a ( x ) , h ( x )) = 1, then a ( x ) g ( x ) is a generator of C . Conversely, if g 1 ( x ) is a generator of C , then there exists a polynomial a ( x ) satisfying gcd( a ( x ) ,h ( x )) = 1 such that g 1 ( x ) ≡ a ( x ) g ( x ) (mod x n − 1). 2716 18. (a) Show that, for any 1 ≤ k ≤ 26, there exists a ternary cyclic code of length 27 and dimension k . (b) Based on the factorization of x 15 − 1 ∈ F 2 [ x ], show that, for any 1 ≤ k ≤ 15, there exists a binary cyclic code of length 15 and dimension k . 2717 Let α be a primitive element of F 2 length 2 m 2718 m and let g ( x ) ∈ F 2 [ x ] be the mini- mal polynomial of α with respect to F 2 . Show that the cyclic code of − 1 with g ( x ) as the generator polynomial is in fact a binary [2 m −1,2 m − 1 − m , 3]-Hamming code. Let C be a binary cyclic code of length n ≥ 3 with generator polynomial g ( x ) /= 1, where n is the smallest positive integer for which x n − 1 is divisible by g ( x ). Show that C has minimum distance at least 3. Is the result true for nonbinary cyclic codes? 2719 Let g ( x ) be the generator polynomial of a binary cyclic code C . Show that the subset C E of even-weight vectors in C is also a cyclic code. Determine the generator polynomial of C E in terms of g ( x ). 2720 1. Let C i be a q -ary cyclic code of length n with generator polynomial g i ( x ), for i = 1 , 2. 1. Show that C 1 ∩ C 2 and C 1 + C 2 are both cyclic codes. 2. Determine the generator polynomials of C 1 ∩ C 2 and C 1 + C 2 in terms of g 1 ( x ) , g 2 ( x ). 2721 22. A codeword e ( x ) of a q -ary cyclic code C of length n is called an idempotent if e 2 ( x ) ≡ e ( x ) (mod x n − 1). If an idempotent e ( x ) is also a generator of C , it is called a generating idempotent . Let g ( x ) be the generator polynomial of a q -ary cyclic code C and put h ( x ) = ( x n − 1) / g ( x ). Show that, if gcd( g ( x ) , h ( x )) = 1, then Chas a unique gener- ating idempotent. In particular, show that, if gcd( n , q ) = 1, then there always exists a unique generating idempotent for a q -ary cyclic code of length n . 2722 Find the generating idempotent for each of the following cyclic codes: 1. the binary [7 , 4]-Hamming code Ham(3 , 2); 2. the binary [15 , 11 , 3]-Hamming code Ham(4, 2); 3. the ternary [13 , 10 , 3]-Hamming code Ham(3, 3). 2723 Let C i be a q -ary cyclic code of length n with generating idempotent e i ( x ) ( i = 1 , 2). Show that C 1 ∩ C 2 and C1 + C 2 have generating idempotents e 1 ( x ) e 2 ( x ) and e 1 ( x ) + e 2 ( x ) − e 1 ( x ) e 2 ( x ), respectively. 2724 An error pattern e of a code C is said to be detectable if e + c /∈ C for all c ∈ C . Show that, for a cyclic code, if an error pattern e ( x ) is detectable, then its i th cyclic shift is also detectable, for any i . 2725 26. Let C be a binary [7 , 4]-Hamming code with generator polynomial g ( x ) = 1 + x + x 3 . Suppose each of the following received words has at most one error. Decode these words using error trapping: (a) 1101011; (b) 0101111; (c) 0100011. 2726 27. (a) 110111101110110; (b) 111110100001000. A binary [15 , 7]-cyclic code is generated by g ( x ) = 1 + x 4 + x 6 + x 7 + x 8 . Decode the following received words using error trapping: 2727 28. A binary [15 , 5]-cyclic code is generated by g ( x ) = 1+ x + x 2 + x 4 + x 5 + x 8 + x 10 . Construct a parity-check matrix of the form ( I 10 | A ). Decode the following words using error trapping: (a) 011111110101000; (b) 100101111011100. 2728 29. Let C be the binary cyclic code of length 15 generated by g ( x ) = 1 + x 2+ x 4+ x 5. 1. Find the minimum distance of C . 2. Show that C can correct all bursts of length 2 or less. 3. Decode the following received words using burst-error-correction: (a) 010110000000010; (b) 110000111010011. 2729 30. Let C be the binary [15 , 9]-cyclic code generated by g ( x ) = 1 + x 3 + x 4 + x 5 + x 6 . Decode the following received words using bursterror- correction: (a) 101011101011100; (b) 010000001011111. 2730 31. Let α be a primitive element of F 2 m ( m > 2) and let g ( x ) ∈ F 2 [ x ] be its minimal polynomial with respect to F 2 . Let C be the binary cyclic code of length 2 m − 1 generated by ( x + 1) g ( x ). An error pattern of the form e ( x ) = x i+ x i+1 is called a double-adjacent-error pattern . Show that no double-adjacent- error patterns can be in the same coset of C. Thus, C can correct all the single-error patterns and double-adjacent-error patterns. 2731 Let g 1 ( x ) , g 2 ( x ) be two polynomials over F q . Let n i be the length of the shortest cyclic code that g i ( x ) generates, for i = 1 , 2. Determine the length of the shortest cyclic code that g 1 ( x ) g 2 ( x ) generates. 2732 1. Let C be a binary cyclic code with generator polynomial g ( x ). 2733 1. Prove that, if g ( x ) is divisible by x − 1, then all the codewords have even weight. 2. Suppose the length of C is odd. Show that the all-one vector is a codeword if and only if g ( x ) is not divisible by x − 1. 3. Suppose the length of C is odd. Show that C contains a codeword of odd weight if and only if the all-one vector is a codeword. Let g ( x ) be the generator polynomial of a q -ary [ n , k ]-cyclic code with gcd( n , q ) = 1. Show that the all-one vector is a codeword if and only if g ( x ) is not divisible by x − 1. 2734 Let C be a q -ary [ q + 1 , 2]-linear code with minimum distance q . Show that, if q is odd, then C is not a cyclic code. 2735 Let n be a positive integer and gcd( n , q ) = 1. Assume that there are exactly t elements in a complete set of representatives of cyclotomic cosets t of q modulo n . Show that there is a total of 2 cyclic codes of length nover F q . 2736 Let a ∈ F ∗ . A q -ary linear code C is called constacyclic with respect to a 37. q if ( , c ,..., c ) belongs to C whenever ( c , c ,..., c ) belongs ac n −1 0 n −2 0 1 n −1 to C . In particular, C is called negacyclic if a = −1. 1. Show that a q -ary linear code C of length n is constacyclic with respect to a if and only if π a ( C ) is an ideal ofF q [ x ] / ( x n − a ), where π a is the map defined by q → F q[ x ] / ( x n F n − a ) , ( c 0 , c 1 ,..., c n − 1 ) 1→ n −1 i =0 c ix i. 2. Determine all the ternary negacyclic codes of length 8. 2737 38. Suppose x n + 1 has the factorization over F q r n pei i (x), i =1 where e i ≥ 1 and p i ( x ) are distinct monic irreducible polynomials. Find the number of q -ary negacyclic codes. Let n be a positive integer with gcd( n , q ) = 1. Let α be a primitive n th root of unity in some extension field ofF q . Let g ( x ) ∈ F q [ x ] be the minimal 2738 polynomial of α with respect to F q . Assume that the degree of g ( x ) ism . Let C be the q -ary cyclic code with generator polynomial g ( x ). Then the dual code C ⊥ is called anirreducible cyclic code . Show that C space (1 , α, α 2 ,..., α n−1 ⊥ is the trace code Tr F q m / F q ( V ), where V is the one-dimensional F q m -vector ) >. 2738 40. Let n be a positive integer and let 1 ≤ l n be a divisor of n . A linear code C over F q is quasi-cyclic of ind e x l (or l-quasi-cyclic ) if ( c n − l , c n − l + 1 ,... , c n − 1 , c 0 , c 1 ,... , c n − l − 1 ) ∈ C whenever ( c 0 , c 1 ,..., c n − 1 ) ∈ C . In particular, a 1-quasi-cyclic code is a cyclic code. 1.Show that the dual of an l -quasi-cyclic code is again l -quasi-cyclic. 2. For every positive integer m , show that there exist self-dual 2-quasi- cyclic codes over F q of length 2 m if qsatisfies one of the following conditions: 1. q is a power of 2; 2. q = p b , where p is a prime congruent to 1 (mod 4); 3. q = p 2 b , where p is a prime congruent to 3 (mod 4). 2740 41. Assume that q ≥ 3 is a power of an odd prime. Let C 1 , C 2 be two linear codes over F q of length n . 1. Using notation as in Exercise 6.6, show that C 1 () C 2 is a quasi-cyclic code of index n . 2. Show that every quasi-cyclic code over F q of length 2 n of index n is of the form C 1 () C 2 for some suitably chosen linear codes C 1 and C 2 over F q . 2741 42. For a prime power q ≥ 2, let 1 m ≤ q − 1 be a divisor of q − 1 and let α ∈ F ∗ be an element of order m . Let C 0 ,C 1 ,... , C m − 1 be linear codes over F q of length l . Show that q r m −1 C := ( x 0 , x 1 ,..., x m − 1 ) : x i = α j =0 ij c j , l where c j ∈ C j for 0 ≤ j ≤ m − 1 is a quasi-cyclic code of length l m of index l . (Note: the code C is called the V andermonde p r oduct of C 0 , C 1 ,... , Cm − 1 .) 2742 43. (a) Let q be an even prime power and let C 1 , C 2 be linear codes over F q of length n . Show that (see Exercise 6.7) C := {( a + x , b + x , a + b + x ) : a , b ∈ C 1 , x ∈ C 2 } is an n -quasi-cyclic code over F q of length 3 n . (b) Let q be a power of an odd prime such that −1 is not a square in F q . Let i be an element of F q 2 such that i 2 + 1 = 0. Let Tr denote the trace Tr F q 2 /Fq defined in Exercise 4.5. Let C 1 , C 2 be linear codes over F q of length l and let C 3 be a linear code of length l over F q 2 . Show that C := { ( c 0 , c 1 , c 2 , c 3 ) : c j = x + (−1) j y + Tr z i j , x ∈ C 1 , y ∈ C 2 , z ∈ C 3 is an l -quasi-cyclic code over F q of length 4 l . 2743 6.1 (a) Given an [ n , k , d ]-linear code over F q , can one always construct an [ n + 1 , k + 1 , d ]-linear code? Justify your answer. (b) Given an [ n , k , d ]-linear code over F q , can one always construct an [ n + 1 , k , d + 1]-linear code? Justify your answer. 2744 2. Let C be a q -ary [ n , k , d ]-linear code. For a fixed 1 ≤ i ≤ n , form the subset A of C consisting of the codewords with the i th position equal to 0. Delete the i th position from all the words in A to form a code D . Show that D is a q -ary [ n − 1 , k t , d t ]-linear code with k − 1 ≤ k t≤ k , d t≥ d . (Note: this way of obtaining a new code is called shortening .) 2745 2.  Suppose that 11110 G = 0 1 0 11 0 0 1 11 is a generator matrix of a binary code C . Find a generator matrix of A with respect to i = 2 using the construction in Exercise 6.2. 2746 Let H i be a parity-check matrix of C i , for i = 1 , 2. 1. Find a parity-check matrix of C 1 ⊕ C 2 and justify your answer. 2. Find a parity-check matrix of the code obtained from the ( u , u + v )- construction and justify your answer. 2747 2. (i) Let A = {0000 , 1100 , 0011 , 1111} be a binary code. Find the code C constructed from A using Corollary 6.1.11. (ii) Let H be a parity-check matrix of A in (i). Find a parity-check matrix of C constructed from A using Corollary 6.1.11. 2748 2.Assume that q is odd. Let C i be an [ n , k i , d i ]-linear code over F q , for i = 1 , 2. Define C 1 () C 2 := {( c 1 + c 2 , c 1 − c 2 ) : c 1 ∈ C 1 , c 2 ∈ C 2 } . d 1 ≤ d ≤ 2 d 2 if 2 d 2 > d 1 . 1. Show that C 1 () C 2 isa [2 n , k 1 + k 2 ]-linear code over F q . 2. If G i is a generator matrix of C i , for i = 1 , 2, find a generator matrix for C 1 () C 2 in terms of G 1 and G 2 . 3. Let d be the distance of C 1 () C 2 . Show that d = 2 d 2 if 2 d 2 ≤ d 1 and 2749 2.Let C i be an [ n , k i , d i ]-linear code over F q , for i = 1 , 2. Define C := {( a + x , b + x , a + b + x ) : a , b ∈ C 1 , x ∈ C 2 } . 1. Show that C isa [3 n , 2 k 1 + k 2 ]-linear code over F q . 2. If G i is a generator matrix of C i , for i = 1 , 2, find a generator matrix of C in terms of G 1 and G 2 . 3. If H i is a parity-check matrix of C i , for i = 1 , 2, find a parity-check matrix of C in terms of H 1 and H 2 . 2750 2. (a) Find the smallest n such that there exists a binary [ n , 50 , 3]-linear code. (b) Find the smallest n such that there exists a binary [ n , 60 , 4]-linear code. 2751 2. Find the smallest n such that there exists an [ n , 40 , 3]-linear code over F 9 . 2. (i) Write down the codewords in R (1 , m ) for m = 3 , 4 , 5. (ii) Verify that R (1 , 3) is self-dual. 2. Show that R ( r , m ) has parameters r 2 m , ( m ) + ( m ) +· · · + ( m ) , 2 m − r 1 . 2. For 0 ≤ r m , show that R ( r , m ) ⊥ = R ( m − 1 − r , m ). 2752 2.Write the binary solutions of the equation x 1 +· · · + x m = 1 as column vectors of F m . Let v 1 ,..., v n be all the solutions of the above equation. Let C m be the binary linear code with 2 G = ( v 1 ,..., v n ) as a generator matrix. 1. Determine all the codewords of C m , for m = 2 , 3 , 4. 2. Find the parameters of C m for all m . 2753 2.For a linear code V over F q , the parameters of V are denoted by length( V ) , dim( V ) and d ( V ):=minimum distance . Suppose we have 1. a code C with length ( C ) = m and dim( C ) = k , and 2. a collection of k codes W 1 ,..., W k , all of them having the same length n . The elements of C are written as row vectors, and the elements of W j are written as column vectors. We fix a basis {c (1) ,..., c ( k ) } of C and denote by G the k × m matrix whose rows are c (1) ,..., c ( k ) . Thus, G is a generator matrix of C. For 1 ≤ j ≤ k , we set C j := { c (1) ,..., c ( j ) } > ⊆ F m . q Then C j is a q -ary code of length m and dimension j . Moreover, C 1 ⊂ C 2 ⊂ ··· ⊂ C k = C . Let M be the set consisting of all the n × k matrices whose j th column belongs to W j , for all 1 ≤ j ≤ k . 1.Show that M is an F q -linear space of dimension }, k i1 = dim( W j ). If we identify an n × m matrix A with a vector a of F mn by putting the 2. q th row of A in the i th block of m positions of a , then the q -ary linear i code has parameters W := { AG : A ∈ M } length ( W ) = mn , dim( W ) = }, k j =1 dim( W j ) , d ( W ) ≥ min{ d ( W j ) · d ( C j ) : 1 ≤ j ≤ k } . 3. By using the binary codes with parameters [2 , 1 , 2], [20 , 19 , 2] and [20 , 14 , 4], show that we can produce a binary [40 , 33 , 4]-linear code. 2754 2. (i) Show that there always exists an [ n , n − 1 , 2]-linear code over F q for any n ≥ 2. (ii) Prove that there is an [ nN , ( n − 1) K , 2 D ]-linear code over F q when- ever there is an [ N , K , D ]-linear code over F q n − 1 . 2755 2. Let α be a root of 1 + x 2 + x 3 ∈ F 2 [ x ]. Consider the map φ : F 8 → F 3 , a 1 · 1 + a 2 · α + a 3 · α 2 f→ ( a 1 , a 2 , a 3 ) . 2 Let A = ( α + 1 , α 2 + 1 , 1) > / F 8 . Determine all the codewords of φ ∗ ( A ) = {( φ ( c 1 ) , φ ( c 2 ) , φ ( c 3 )) : ( c 1 , c 2 , c 3 ) ∈ A }. 2756 2. Consider the linear code A := {(1 , 1) , ( α, 1 + α )} > over F 4 , where α is a root of 1 + x + x 2 ∈ F 2 [ x ]. Let B be the binary code {0000 , 1100 , 1010 , 0110} and consider the F 2 -linear transformation between F 4 and B defined by φ : 0 f→ 0000 , 1 f→ 1100 , α f→ 1010 , 1 + α f→ 0110 . Determine all the codewords of the code C := φ ∗ ( A ) = {( φ ( c 1 ) , φ ( c 2 )) : ( c 1 , c 2 ) ∈ A } . 2757 Let Ham( m , 4) be a Hamming code of length (4 m − 1) / 3 over F 4 . Using Theorem 6.3.5, estimate the parameters of Ham( m , 4)| F 2 . Find the exact parameters of Ham(3 , 4)| F 2 . 2758 Let C = {(1 , α, α 2 ) , ( α 2 , α, 0)} > be a linear code over F 4 , where α is a root of 1 + x + x 2 ∈ F 2 [ x ]. Determine all the codewords of C | F . 2 2759 2.(i) Suppose that u 1 ,..., u r are vectors of F n . Show that the set q { u 1 ,..., u r } is F q -linearly independent if and only if it is F q m -linearly independent for all m ≥ 1. (ii) Show that, for an [ N , K ]-linear code C over F q m , the subfield subcode C | F q has dimension at most K . Moreover, show that dim F q ( C | F q ) = K if and only if there is an F q m -basis { c 1 ,..., c K } of C such that c i ∈ F N for all i = 1 ,..., K . q 2760 2. Show that dim F q (Tr F q m / F q ( C )) ≥ dim F q m ( C ) for any linear code C over F q m . 2.(i) Show that, for a polynomial f ( x ) ∈ F q [ x ] and an element α ∈ F q 2 , one has ( f ( α )) q + f ( α ) ∈ F q and ( f ( α )) q + 1 ∈ F q . 2. Show that the set S m = { x i ( q + 1) ( x jq + x j ) : i ( q + 1) + jq ≤ ( q + 1) m } has ( m + 1)( m + 2) / 2 elements. Moreover, show that the vector space V m = S m > spanned by S m over F q has dimension | S m | = ( m + 1)( m + 2) / 2. For an element β ∈ F q 2 \ F q , we have β q /= β . Thus, we can label all the elements of F q 2 \ F q as follows: 2. F q 2 \ F q = { β 1 , β q ,..., β n ,β q } , 1n where n = ( q 2 − q ) / 2. Show that, for m q − 1, the code C m = {( g ( β 1 ) ,..., g ( β n )) : g ∈ V m } is an [ n , ( m + 1)( m + 2) / 2 , d ]-linear code over F q with d ≥ n − m ( q + 1) / 2. 2761 2. Let A be an [ N , K , D ]-linear code over F q m and let B be an [ n , m , d ]- linear code over F q . We set up an F q -linear transformation φ between F q m and B such that φ is bijective. We extend the map φ and obtain a map φ ∗: F N q m → F nN , ( v 1 ,..., v N ) f→ ( φ ( v 1 ) ,..., φ ( v N )) . Show that the code q ( B ⊥ ) N := {( c 1 ,..., c N ) : c i ∈ B ⊥ } is contained in ( φ ∗ ( A )) ⊥ . 2762 2. Let C be a q m -ary linear code. Show that dim F q m ( C ) − ( m − 1)( n − dim F q m ( C )) ≤ dim F q ( C | F q ) ≤ dim F q m ( C ) and dim F q m ( C ) ≤ dim F q (Tr F q m / F q ( C )) ≤ m · dim F q m ( C ) . 2763 2. Let C be a q m -ary linear code of length n and let U be an F q m -subspace of C with the additional property U q⊆ C , where U q = {( u q ,..., u q ) : ( u 1 ,..., u n ) ∈ U } . 1n Show that dim F q (Tr F q m / F q ( C )) ≤ m (dim F q m ( C ) − dim F q m ( U )) + dim F q ( U | F q ) . 2764 2. Let C be a q m -ary linear code of length n and let V be an F q m -subspace of C ⊥ with the additional property Vq ⊆ C ⊥ . Show that dim F q ( C | F q ) ≥ dim F q m ( C ) − ( m − 1)( n − dim F q m ( C ) − dim F q m ( V )) . 2765 2.Let C be a q m -ary linear code of length n . Show that the following three conditions are equivalent: 1. C q= C ; 2. dim F q ( C | F q ) = dim F q m ( C ); 3. Tr F q m / F q ( C ) = C | F q . 2766 2. (Alphabet extension.) Let s and r be two integers such that s ≥ r > 1. We embed an alphabet A of cardinality rinto an alphabet B of cardinality s . For an ( n , M , d )-code C over A , consider an embedding C c → A nc → B n. The code C can be viewed as a subset of B n and therefore a code over B . Show that the code C still has parameters ( n , M , d ) when viewed as a code over B . 2767 2. Let r and s be two integers bigger than 1. Let C 1 be an ( n , M 1 , d 1 )-code over Z r , and let C 2 be an ( n , M 2 , d2 )-code over Z s . We embed Z r ( Z s , respectively) into Z rs by mapping ( i (mod r )) ∈ Z r (( i (mod s )) ∈ Z s , respectively) to ( i (mod rs )) ∈ Z rs . Then bothC 1 and C 2 can be viewed as codes over Z rs . Show that the code C 1 + rC 2 := f a + r b ∈ Z n rs : a ∈ C 1, b ∈ C 21 is an ( n , M 1 M 2 , min{ d 1 , d 2 })-code over Z rs . 2768 2. (Alphabet restriction.) Let s and r be two integers such that s ≥ r > 1. We embed an alphabet A of cardinalityr into Z s . For an ( n , M , d )-code C over Z s , consider all the s n shifts C v := { v + c : c ∈ C } for all v ∈ Z n . Show that there exists a vector v 0 ∈ Z n such that the intersection s C v0 s ∩ A n is an r -ary ( n , M t , d t )-code with M t ≥ M ( r / s ) n , and d t ≥d. 2769 2770 Find the size, (minimum) distance, information rate and relative minimum distance of each of the following codes: 1. the binary code of all the words of length 3; 2. the ternary code consisting of all the words of length 4 whose second and fourth coordinates are 0; 3. the code over the alphabet F p ( p prime) consisting of all the words of length 3 whose first coordinate isp − 1 and whose second coordinate is 1; 4. the repetition code over the alphabet F p ( p prime) consisting of the following words of length n : (0 , 0,..., 0) , (1 , 1 ,..., 1) ,..., ( p − 1 , p − 1 ,..., p − 1). 4. For n odd, let C be a self-orthogonal binary [ n, ( n − 1) / 2]-code. Show that C ⊥ is a self-dual code. (Note: compare with Exercise 4.26.) Without using any of the bounds discussed in this chapter, show that (a) A 2 (6 , 5) = 2 , (b) A 2 (7 , 5) = 2. (Hint: For (a), first show that A 2 (6 , 5) ≥ 2 by producing a code explicitly. Then try to show that A 2 (6 , 5) ≤ 2 using a simple combinatorial argument similar to the one in Example 5.2.5.) 2771 5. Find an optimal binary code with n = 3 and d = 2. 5. Prove that A q ( n, d ) ≤ q A q ( n − 1 , d ). 2772 7. For each of the following spheres in A n = F n , list its elements and 2 compute its volume: (a) S A (110 , 4), (b) S A (1100 , 3), (c) S A (10101 , 2). 2773 2774 8. For each n such that 4 ≤ n ≤ 12, compute the Hamming bound and the sphere-covering bound for A 2 ( n, 4). 8. Prove that a (6 , 20 , 4)-code over F 7 cannot be an optimal code. 10. Let q ≥ 2 and n ≥ 2 be any integers. Show that A q ( n, 2) = q n − 1 . 10. Let C be an [ n, k, d ]-code over F q , where gcd( d, q ) = 1. Suppose that all the codewords of C have weight congruent to 0 or d modulo q . Using Exercise 4.30(iv), or otherwise, show the existence of an [ n + 1 , k, d + 1]- code over F q . 2775 Let C be an optimal code over F 11 of length 12 and minimum distance 2. Show that C must have a transmission rate of at least 5 / 6. 2776 13. i=0 For positive integers n, M, d and q > 1 (with 1 ≤ d ≤ n ), show that, if ( M − 1) ), d − 1 ( n ) ( q − 1) i q n , then there exists a q -ary ( n, M )- i code of minimum distance at least d . (Note: this is often known as the Gilbert–Varshamov bound for nonlinear codes.) 2777 2778 Determine whether each of the following codes exists. Justify your answer. 1. A binary code with parameters (8 , 29 , 3). 2. A binary linear code with parameters (8 , 8 , 5). 3. A binary linear code with parameters (8 , 5 , 5). 4. A binary linear code with parameters (24 , 2 12 , 8). 5. A perfect binary linear code with parameters (63 , 2 57 , 3). 15. Write down a parity-check matrix H for a binary Hamming code of length 15, where the j th column of H is the binary representation of j . Then use H to construct a syndrome look-up table and use it to decode the following words: (a) 01010 01010 01000, (b) 11100 01110 00111, (c) 11001 11001 11000. 2779 16. (i) Show that there exist no binary linear codes with parameters [2 m , 2 m − m, 3], for any m ≥ 2. (ii) Let C be a binary linear code with parameters [2 m , k, 4], for some m ≥ 2. Show that k ≤ 2 m − m − 1. 2780 1. Prove Proposition 5.3.15. 2. (i) Let n ≥ 3 be an integer. Show that there is an [ n, k, 3]-code defined over F q if and only if q n − k − 1 ≥ ( q − 1)n . 3. Find the smallest n for which there exists a ternary [ n, 5 , 3]-code. 2782 19. (i) Let v be a nonzero vector in F r . Show that the set of vectors in q q orthogonal to v , i.e., { v } ⊥ F r q r − 1. , forms a subspace of F r of dimension Let G be a generator matrix for the simplex code S ( r, q ). Show that, for a given nonzero vector v ∈ F r , there are exactly ( q r − 1 −1) / ( q −1) 2. q columns c of G such that v · c = 0. Using the observation that S ( r, q ) = { v G : v ∈ F r }, 2. or otherwise, show that every nonzero codeword of S ( r, q q ) has weight q r − 1 . (Hint: Use (ii) to determine the number of coordinates of v G that are equal to 0.) 2782 Determine the Hamming weight enumerators of Ham(3 , 2) and S (3 , 2). Verify that they satisfy the MacWilliams identity (see Exercise 4.49). 2783 1. The ternary Hamming code Ham(2 , 3) is also known as the tetracode . 1. Show that the tetracode is a self-dual MDS code. 2. Without writing down all the elements of Ham(2 , 3), determine the weights of all its codewords. 3. Determine the Hamming weight enumerator of Ham(2 , 3) and show that the MacWilliams identity (see Exercise 4.49) holds for C = C ⊥ = Ham(2 , 3). 2784 1. Let G 6 denote the hexacode defined in Exercise 4.10(b). 1. Show that G 6 is a [6 , 3 , 4]-code over F 4 . (Hence, G 6 is an MDS quaternary code.) 2. Let G t be the code obtained from G 6 by deleting the last coordinate 6 from every codeword. Show that G t 6 is a Hamming code over F 4. 2785 23. (i) Show that the all-one vector (1 , 1 ,..., 1) is in the extended binary Golay code G 24 . (ii) Deduce from (i) that G 24 does not have any word of weight 20. 24. Prove Proposition 5.3.22. 2786 (i) Show that every word of weight 4 in F 23 is of distance 3 from exactly one codeword in the binary Golay code G 23 . 1. 2 2. Use (i) to count the number of codewords of weight 7 in G 23 . 2. Use (ii) to show that the extended binary Golay code G 24 contains precisely 759 codewords of weight 8. 2787 26. Show that the extended binary Golay code G 24 has the weight distribution shown in Table 5.5 for its codewords. 26. Verify the MacWilliams identity (see Exercise 4.49) with C = C ⊥ = G 24 . Table 5.5. Weight 0 4 8 12 16 20 24 Number of codewords 1 0 759 2576 759 0 1 2788 28. Prove that the extended ternary Golay code G 12 is a [12 , 6 , 6]-code. 28. Show that the ternary Golay code G 11 satisfies the Hamming bound. 2789 30. Prove Theorem 5.5.3. (Hint: When d is even and n 2 d , mimic the proof of Theorem 5.5.2. Divide into the two cases M even and M odd, and maximize the expression ), n i1 = ), a∈F2 n i,a ( M − n i,a ) in each case. For the case of even d and n = 2 d , apply Exercise 5.6, with q = 2, and the previous case. When d is odd, apply Theorem 5.1.11 with the result for even d .) 2790 31. Let C be the code over F 4 = {0 , 1 , α, α 2 } with generator matrix r 1011\ 0 1 α α 2. 1. Show that C is an MDS code. 2. Write down a generator matrix for the dual C ⊥ . 3. Show that C ⊥ is an MDS code. 2791 32. 32. Show that the only binary MDS codes are the trivial ones. Suppose there is a q -ary MDS code C of length n and dimension k , where kn. 1. Show that there is also a q -ary MDS code of length n − 1 and dimension k . 2. For a given 1 ≤ i ≤ n , let C i be the subcode of C consisting of all the codewords with 0 in the i th position, and let D i be the code obtained by deleting the i th coordinate from every codeword of C i . Show that D i is an MDS code. (Hint: You may need to show that there is at least one minimum weight codeword of C with 0 in the i th position.) 2792 For each n such that 9 ≤ n ≤ 16, compare the Singleton, Plotkin and Hamming upper bounds for A 2 ( n, 9). 2793 1. Suppose there exists a binary linear code C of parameters [16 , 8 , 6]. 1.Let C t be the residual code of C with respect to a codeword of weight 6. Show that C t is a binary linear code of parameters [10 , 7 , d t ], where 3 ≤ d t ≤ 4. Use Exercise 5.32 to show that d t = 3. 2. 2. Using the Hamming bound, or otherwise, show that such a C t cannot exist. 2794 36. A binary ( n, M, d )-code C is called a constant-weight binary code if there exists an integer w such that wt( c ) = wfor all c ∈ C . In this case, we say that C is a constant-weight binary ( n, M, d ; w )-code. 1. Show that the minimum distance of a constant-weight binary code is always even. 2. Show that a constant-weight binary ( n, M, d ; w )-code satisfies M ≤ ( n) . w 3. Prove that a constant-weight binary ( n, M, d ; w )-code can detect at least one error. 2795 37. Let A 2 ( n, d, w ) be the maximum possible number M of codewords in a constant-weight binary ( n, M, d ; w )-code. Show that (a) 1 ≤ A 2 ( n, d, w ) ≤ ( n ) ; w (b) A 2 ( n, 2 , w ) = ( n ) ; w (c) A 2 ( n, d, w ) = 1 for d > 2 w ; (d) A 2 ( n, d, w ) = A 2 ( n, d, n − w ). 2796 38. Use the Griesmer bound to find an upper bound for d for the q -ary linear codes of the following n and k : (a) q = 2, n = 10 and k = 3; (b) q = 3, n = 8 and k = 4; (c) q = 4, n = 10 and k = 5; (d) q = 5, n = 9 and k = 2. 2797 [( q k For a prime power q and positive integers k and u with k > u > 0, the MacDonald code C k,u is a q -ary linear code, of parameters −q u ) / ( q − 1) , k, q k−1 −q u−1 ], that has nonzero codewords of only two possible weights: q k−1 −q u−1 and q k−1 . Show that the MacDonald codes attain the Griesmer bound. 2798 Let C be an [ n, k, d ]-code over F q and let c ∈ C be a codeword of weight w , where w dq/ ( q − 1). Show that the residual code Res( C, c ) is an t t [ n − w, k − 1 , d ]-code, where d ≥ d − w + r w/q l. 2799 1. Let C bea [ q 2 , 4 , q 2 − q − 1]-code over F q . 1.By considering Res( C, c ), where wt( c ) = q 2 − t with 2 ≤ t ≤ q − 1, or otherwise, show that the only possible weights of the codewords in C are: 0, q 2 − q − 1, q 2 − q , q 2 − 1 and q 2 . Show the existence of a [ q 2 + 1 , 4 , q 2 − q ]-code over F q . (Hint: 2. Compare with Exercise 5.11.) 2800 43. Show that the Krawtchouk polynomials satisfy the following recurrence relation: ( k + 1) K k + 1 ( x ) = ( k + ( q − 1)( n − k ) − qx ) K k ( x ) − ( q − 1)( n − k + 1) K k − 1 ( x ) . 44. Show that K k ( x ) = ), k (− q ) j ( q − 1) k − j ( n − j )( x ) . 2801 45. Let q = 2. Show that: (a) K 0 ( x ) = 1; j =0 k−jj (b) K 1 ( x ) = −2 x + n ; (c) K 2 ( x ) = 2 x 2 − 2 nx + ( n ) ; 2 (d) K 3 ( x ) = −4 x 3 / 3 + 2 nx 2 − ( n 2 − n + 2 / 3) x + ( n ) . 3 2802 46. Let be a primitive th root of unity in C . Suppose u ∈ Z n is a word of q ζq weight i . Show that ) w∈Zn q wt( w )= k ζ u·w= K k( i ) , where, for u = ( u 1 ,..., u n ) and w = ( w 1 ,..., w n ), u · w = u 1 w 1 + ··· + u n w n . 2803 Use the linear programming bound (Theorem 5.8.7) to show that the Hadamard matrix code of parameters (2d, 4 d, d ), with d even, is an op- timal code. (Hint: Use f ( x ) = 1 + K 1 ( x ) + 1 K 2 ( x ).) d 2804 48. Let d be such that 2 d > n . Use the linear programming bound (Theorem 5.8.7) to show that A 2 ( n, d ) ≤ 2 d/ (2 d − n ). Note that this bound is slightly weaker than the Plotkin bound. (Hint: Use f ( x ) = 1 1 K ( x ).) +1 2d−n 2805 1. Prove Proposition 4.1.6. 2. For each of the following sets, determine whether it is a vector space over the given finite field F q . If it is a vector space, determine the number of distinct bases it can have. (a) q = 2, S = {( a , b , c , d , e ) : a + b + c + d + e = 1}, (b) q = 3, T = {( x , y , z , w ) : xyz w = 0}, (c) q = 5, U = {( λ + µ, 2 µ, 3 λ + ν, ν ) : λ, µ, ν ∈ F 5 }, (d) q prime, V = {( x 1 , x 2 , x 3 ) : x 1 = x 2 − x 3 }. 2806 3. For any given positive integer n and any 0 ≤ k ≤ n , determine the number of distinct subspaces of F n of dimension k . 3. (a) Let F q be a subfield of F r . Show that F r is a vector space over F q , where the vector addition and the scalar multiplication are the q same as the addition and multiplication of the elements in the field F r , respectively. (b) Let α be a root of an irreducible polynomial of degree m over F q . Show that {1 , α, α 2 ,..., α m − 1 } is a basis of F qm over F q . q 2807 5.Define Tr F q m / F q ( α ) = α + α +· · · + α q m −1 for any α ∈ F q m . The element Tr F q m / F q ( α ) is called the trace of α with respect to the extension F q m / F q . 1. Show that Tr F q m / F q ( α ) is an element of F q for all α ∈ F q m . 2. Show that the map Tr F q m / F q : F q m → F q , α i→ Tr F q m / F q ( α ) is an F q -linear transformation, where both F q m and F q are viewed as vector spaces over F q . 3. Show that Tr F q m / F q is surjective. 3. Let β ∈ F q m . Prove that Tr F q m / F q ( β ) = 0 if and only if there exists an element γ ∈ F q m such that β = γ q −γ . (Note: this statement is commonly referred to as the additive form of Hilbert’s Theorem 90.) 5. (Transitivity of trace.) Prove that Tr F q rm / F q ( α ) = Tr F q m / F q (Tr F q rm / F q m ( α )) for any α ∈ F q rm . 2808 6. (a) Let V be a vector space over a finite field F q . Show that ( λ u + µ v )· w = λ ( u · w ) + µ ( v · w ), for all u , v , w ∈ V and λ, µ ∈ F q . 2. Give an example of a finite field F q and a vector u defined over F q with the property that u /= 0 but u · u = 0. 2. Let V be a vector space over a finite field F q and let { v 1 , v 2 ,..., v k } be a basis of V . Show that the following two statements are equivalent: 1. v · v t = 0 for all v , v t ∈ V , 2. v i · v j = 0 for all i , j ∈ {1 , 2 ,..., k }. (Note: this shows that it suffices to check (ii) when we need to deter- mine whether a given linear code is self-orthogonal.) 2809 q Let F q be a finite field and let S be a subset of F n . 1. Show that S ⊥ and S > ⊥ are subspaces of F n . 2. Show that S ⊥ = S > ⊥ . q 2810 8. For each of the following sets S and corresponding finite fields F q , find the F q -linear span S > and its orthogonal complement S ⊥ : (a) S = {101 , 111 , 010}, q = 2, (b) S = {1020 , 0201 , 2001}, q = 3, (c) S = {00101 , 10001 , 11011}, q = 2. Problems 4.9 to 4.13 deal with some well known inner products other than the Euclidean inner product. 2811 9. q Let ( , ) H : F n n 2 ×F q 2 → F q 2 be defined as n ( u , v ) H= )u iv q, i i =1 where u = ( u 1 ,..., u n ) , v = ( v 1 ,..., v n ) ∈ F n . Show that ( , ) H q 2 F n is an inner product on q2 . (Note: this inner product is called the Hermitian inner product . For a linear code C over F q 2 , its Hermitian dual is defined as C ⊥H= { v ∈ F n q 2 :(v,c)H = 0 for all c ∈ C } . If C = C ⊥ H , then we say C is self-dual with respect to the Hermitian inner product.) 2812 10. Write F 4 = {0 , 1 , α, α 2 } (cf. Example 3.3.5). Show that the following linear codes over F 4 are self-dual with respect to the Hermitian inner product: (a) C 1 = {(0 , 0) , (1 , 1) , ( α, α ) , ( α 2 , α 2 )}; (b) C 2 is the F 4 -linear code with generator matrix  1001αα 0 1 0 α 1 α . 0 0 1 α α1 (Note: the code C 2 is called the hexacode .) Are C 1 and C 2 self-dual with respect to the Euclidean inner product? 11. Let ( , ) S : F 2 n × F 2 n → F q be defined as qq (( u , v ) , ( u t , v t )) S = u · v t − v · u t , where u , v , u t , v t ∈ F n and · is the Euclidean inner product on F n . Show q that ( , ) S is an inner product on F 2 n q q . (Note: this inner product is called the symplectic inner product . It is useful in the construction of quantum error-correcting codes.) 2813 13. Let C be a linear code over F q with a generator matrix ( I n | A ), where I n is the n × n identity matrix and A is an n × n matrix satisfying A = A T . 1. Show that C is self-dual with respect to the symplectic inner product ( , ) S , i.e., C = C ⊥ S , where C ⊥S= { v ∈ F 2n q : ( v , c ) S = 0 for all c ∈ C } . Show that C is equivalent to C ⊥ , its dual under the usual Euclidean inner product. 2. 2814 14. Determine which of the following codes are linear over F q : (a) q = 2 and C = {1101 , 1110 , 1011 , 1111}, (b) q = 3 and C = {0000 , 1001 , 0110 , 2002 , 1111 , 0220 , 1221 , 2112 , 2222}, (c) q = 2 and C = {00000 , 11110 , 01111 , 10001}. 2815 15. Let C and D be linear codes over F q of the same length. Define C+D={c+d:c∈C,d∈D}. Show that C + D is a linear code and that ( C + D ) ⊥ = C ⊥ ∩ D ⊥ . 2816 1. Determine whether each of the following statements is true or false. Justify your answer. 1.If C and D are linear codes over F q of the same length, then C ∩ D is also a linear code over F q . If C and D are linear codes over F q of the same length, then C ∪ D 2. is also a linear code over F q . If C = S > , where S = { v 1 , v 2 , v 3 }⊆ F n , then dim( C ) = 3. 3. q 3. If C = S > , where S = { v 1 , v 2 , v 3 }⊆ F n , then q d ( C ) = min{wt( v 1 ) , wt( v 2 ) , wt( v 3 )} . If C and D are linear codes over F q with C ⊆ D , then D ⊥ ⊆ C ⊥ . 5. 2817 17. Determine the number of binary linear codes with parameters [ n , n −1 , 2] for n ≥ 2. 17. Prove Lemma 4.3.6. 2818 19. Let u ∈ F n . A binary code C of length n is said to correct the error 2 if and only if, for all c , c t ∈ C with c t /= c , we have d ( c , c + u ) d ( c t , c + u ). Assume that u 1 , u 2 ∈ F n agree in at least the positions where 1 occurs in . Suppose that C corrects the error pattern u . Prove that u 2 u 12 pattern C also corrects the error pattern u 1 . 2819 20. (i) Let x , y ∈ F n . If x and y are both of even weight or both of odd 2 weight, show that Let x , y ∈ F n 2. x+y must have even weight. , y has even weight and the other 2 . If exactly one of x has odd weight, show that x + y must have odd weight. 2. Using (i) and (ii), or otherwise, prove that, for a binary linear code C , either all the codewords have even weight or exactly half of the codewords have even weight. 2820 21. Let C be a binary linear code of parameters [ n , k , d ]. Assume that C has at least one codeword of odd weight. Let C t denote the subset of C consisting of all the codewords of even weight. Show that C t is a binary linear code of parameters [ n , k − 1 , d t ], with d t > d if d is odd, and d t = d if d is even. (Note: this is an example of an expurgated code.) 2821 1. (a) Show that every codeword in a self-orthogonal binary code has even weight. 2. Show that the weight of every codeword in a self-orthogonal ternary code is divisible by 3. 2. Construct a self-orthogonal code over F 5 such that at least one of its codewords has weight not divisible by 5. 2. Let x , y be codewords in a self-orthogonal binary code. Suppose the weights of x and y are both divisible by 4. Show that the weight of x + y is also a multiple of 4. 2822 Let C be a self-dual binary code with parameters [ n , k , d ]. 1. Show that the all-one vector (1 , 1 ,..., 1) is in C . 2. Show that either all the codewords in C have weight divisible by 4; or exactly half of the codewords in Chave weight divisible by 4 while the other half have even weight not divisible by 4. 3. Let n = 6. Determine d . 24. Give a parity-check matrix for a self-dual binary code of length 10. 24. Prove that there is no self-dual binary code of parameters [10 , 5 , 4]. 2823 For n odd, let C be a self-orthogonal binary [ n , ( n − 1) / 2]-code. Let 1 denote the all-one vector of length nand let 1 + C = { 1 + c : c ∈ C }. Show 2824 that C ⊥ = C ∪ ( 1 + C ). 2825 Let C be a linear code over F q of length n . For any given i with 1 ≤ i ≤ n , show that either the i th position of every codeword of C is 0 or every element α ∈ F q appears in the i th position of exactly 1 / q of the codewords of C . 2826 28. Let C be a linear code over F q of parameters [ n , k , d ] and suppose that, for every 1 ≤ i ≤ n , there is at least one codeword whose i th position is nonzero. 1. Show that the sum of the weights of all the codewords in C is n ( q − 1) q k − 1 . Show that d ≤ n ( q − 1) q k − 1 / ( q k − 1). 2. 2. Show that there cannot be a binary linear code of parameters [15 , 7 , d ] with d ≥ 8. 2827 29. Let x , y be two linearly independent vectors in F n and let z denote the q number of coordinates where x , y are both 0. 1. Show that wt( y ) + }, λ∈Fq wt( x + λ y ) = q ( n − z ). 2. Suppose further that x , y are contained in an [ n , k , d ]-code C over F q . Show that wt( x ) + wt( y ) ≤ qn − ( q − 1) d . 2828 31. Find a generator matrix and a parity-check matrix for the linear code generated by each of the following sets, and give the parameters [ n , k , d ] for each of these codes: (a) q = 2, S = {1000 , 0110 , 0010 , 0001 , 1001}, (b) q = 3, S = {110000 , 011000 , 001100 , 000110 , 000011}, (c) q = 2, S = {10101010 , 11001100 , 11110000 , 01100110 , 00111100}. 2829 32. Assign messages to the words in F 3 as follows: 2 000 100 010 001 110 101 011 111 ACDEGINO Let C be the binary linear code with generator matrix  10101  G =  01010  . 00011 Use G to encode the message ENCODING. 2830 33. Find a generator matrix G t in standard form for a binary linear code equivalent to the binary linear code with the given generator matrix G :  101010 (a) G =  0 1 0 1 0 1  , (b) G =  101100111 000101100.  1 1 0 1 1 0   001011 000101110 2831 34. Find a generator matrix G t in standard form for a binary linear code C t equivalent to the binary linear code Cwith the given parity-check matrix H :  11000  0101110 (a) H =  0 1 1 0 1  , (b) H =  1 1 1 1 0 0 0  . 00011 0110101 2832 35. Construct a binary code C of length 6 as follows: for every ( x 1 , x 2 , x 3 ) ∈ 2 , construct a 6-bit word ( x 1 , x 2 , x 3 , x 4 , x 5 , x 6 ) ∈ C , where F 3 x 4= x 1+ x 2+ x 3, x 5= x 1+ x 3, x 6= x 2+ x 3. 1. Show that C is a linear code. 2. Find a generator matrix and a parity-check matrix for C . 2833 36. Construct a binary code C of length 8 as follows: for every ( a , b , c , d ) ∈ 2 , construct an 8-bit word ( a , b , c , d , w, x , y , z ) ∈ C , where F 4 w=a+b+c,x=a+b+d,y=a+c+d,z=b+c+d. 3. 1. Show that C is a linear code. 2. Find a generator matrix and a parity-check matrix for C . Show that C is exactly three-error-detecting and one-error- correcting. 2834 37. (a) Prove that equivalent linear codes always have the same length, di- mension and distance. (b) Show that, if C and C t are equivalent, then so are their duals C ⊥ and ( C t ) ⊥ . 2835 Suppose that an ( n − k ) × n matrix H is a parity-check matrix for a linear code C over F q . Show that, if M is an invertible ( n − k ) × ( n − k ) matrix with entries in F q , then MH is also a parity-check matrix for C . 2836 39.  0111000   1101000  (a) H =  Find the distance of the binary linear code C with each of the following given parity-check matrices: 1110100  , (b) H =  1010100  .  1100010   0110010   1010001  1100001 2837 Let n ≥ 4 and let H be a parity-check matrix for a binary linear code C of length n . Suppose that the columns ofH are all distinct and that the weight of every column of H is odd. Show that the distance of C is at least 4. 2838 41. List the cosets of each of the following q -ary linear codes: (a) q = 3 and C 3 = {0000 , 1010 , 2020 , 0101 , 0202 , 1111 , 1212 , 2121 , 2222}, (b) q = 2 and C 2 = {00000 , 10001 , 01010 , 11011 , 00100 , 10101 , 01110 , 11111}. 2839 Let H denote the parity-check matrix of a linear code C . Show that the coset of C whose syndrome is vcontains a vector of weight t if and only if v is equal to some linear combination of t columns of H . 2840 43. For m , n satisfying 2 m − 1 ≤ n 2 m , let C be the binary [ n , n − m ]-code whose parity-check matrix H has as its ith column (1 ≤ i ≤ n ) the binary representation of i (i.e., the first column is (0 ... 01) T , the second column is (0 ... 010) T and the third column is (0 ... 011) T , etc.). Show that every coset of C contains a vector of weight ≤2. 2841 44. Let C ⊆ F n be a linear code with distance d . Show that a word x ∈ F n is qq the unique coset leader of x + C if wt( x ) ≤ L( d − 1) / 2J. 2842 45. Let C be a linear code of distance d , where d is even. Show that some coset of C contains two vectors of weight e + 1, where e = L( d − 1) / 2J. 2843 46. Show that ( 1020 \ 0102 is a parity-check matrix for C 3 in Exercise 4.41 and that ( 10001 \ 01010 is a parity-check matrix for C 2 in Exercise 4.41 . Using these parity-check matrices and assuming complete decoding, construct a syndrome look-up table for each of C 3 and C 2 . 2844 47. Let C be the binary linear code with parity-check matrix  110100  H =  101010  . 011001 Write down a generator matrix for C and list all the codewords in C . Decode the following words: (a) 110110, (b) 011011, (c) 101010. 2845 Let f ( x ) = (2 + 2 x 2 )(2 + x 2 + x 3 ) 2 (−1 + x 4 ) ∈ F 3 [ x ] and g ( x ) = (1 + x 2 )(−2 + 2 x 2 )(2 + x 2 + x 3 ) ∈ F 3 [ x ]. Determine gcd( f ( x ) , g ( x )) and lcm( f ( x ) , g ( x )). 2846 9. Find two polynomials u ( x ) and v ( x ) ∈ F 2 [ x ] such that deg( u ( x )) 4, deg( v ( x )) 3 and u ( x )(1 + x + x 3 ) + v ( x )(1 + x + x 2 + x 3 + x 4 ) = 1 . 2847 9. Construct both the addition and multiplication tables for the ring 9. (a) Find the order of the elements 2 , 7 , 10 and 12 in F 17 . F 3 [ x ] / ( x 2 + 2). (b) Find the order of the elements α, α 3 ,α + 1 and α 3 + 1 in F 16 , where α is a root of 1 + x + x 4 . 2848 9. (i) Let α be a primitive element of F q . Show that α i is also a primitive element if and only if gcd( i , q − 1) = 1. (ii) Determine the number of primitive elements in the following fields: F 9 , F 19 , F 25 and F 32 . 2849 9. Determine all the primitive elements of the following fields: F 7 , F 8 and F 9 . 9. Show that all the nonzero elements, except the identity 1, in F 128 are primitive elements. 2850 1. 9. Show that any root of 1 + x + x 6 ∈ F 2 [ x ] is a primitive element of F 64 . 9. Consider the field with 16 elements constructed using the irreducible polynomial f ( x ) = 1 + x 3 + x 4 over F 2 . Let α be a root of f ( x ). Show that α is a primitive element of F 16 . Represent each element both as a polynomial and as a power of α . 2. Construct a Zech’s log table for the field. Q6 9. Find a primitive element and construct a Zech’s log table for each of the following finite fields: (a) F 3 2 , (b) F 2 5 , (c) F 5 2 . 2851 9. Show that each monic irreducible polynomial of F q [ x ] of degree m is the minimal polynomial of some element of F q m with respect to F q . 9. Let α be a root of 1 + x 3 + x 4 ∈ F 2 [ x ]. 1. List all the cyclotomic cosets of 2 modulo 15. 2. Find the minimal polynomial of α i ∈ F 16 , for all 1 ≤ i ≤ 14. 3. Using Exercise 3.18, find all the irreducible polynomials of degree 4 over F 2 . 9. (i) Find all the cyclotomic cosets of 2 modulo 31. 2852 (ii) Find the minimal polynomials of α , α 4 and α 5 , where α is a root of 1 + x 2 + x 5 ∈ F 2 [ x ]. 2853 2854 Based on the cyclotomic cosets of 3 modulo 26, find all the monic irre- ducible polynomials of degree 3 over F3 . 9. (i) Prove that, if k is a positive divisor of m , then F p m contains a unique subfield with p k elements. (ii) Determine all the subfields in (a) F 2 12 , (b) F 2 18 . 2855 9. Factorize the following polynomials: (a) x 7 − 1 over F 2 ; (b) x 15 − 1 over F 2 ; (c) x 31 − 1 over F 2 ; (d) x 8 − 1 over F 3 ; (e) x 12 − 1 over F 5 ; (f) x 24 − 1 over F 7 . 2856 9. Show that, for any given element c of F q , there exist two elements a and b of F q such that a 2 + b 2 = c . 2857 9. For a nonzero element b of F p , where p is a prime, prove that the trinomial x p − x − b is irreducible in F p n [ x ] if and only if n is not divisible by p . 2858 9. (Lagrange interpolation formula.) For n ≥ 1, let α 1 ,..., α n be n distinct elements of F q , and let β 1 ,..., β n be n arbitrary elements of F q . Show that there exists exactly one polynomial f ( x) ∈ F q [ x ] of degree ≤ n − 1 such that f ( α i ) = β i for i = 1 ,..., n . Furthermore, show that this polynomial is given by n βin f ( x ) = )( x − α k) , n i=1g t (αi)k 1 = k /= i where g t ( x ) denotes the derivative of g ( x ) := n n k =1 2859 ( x − α k ). 9. (i) Show that, for every integer n ≥ 1, the product of all monic irreducible polynomials over F q whose degrees divide n is equal to x q n −x. (ii) Let I q ( d ) denote the number of monic irreducible polynomials of degree d in F q [ x ]. Show that q n = ) d I q ( d ) for all n ∈ N , d|n where the sum is extended over all positive divisors d of n . 2860 9.The Mo¨bius function on the set N of positive integers is defined by  1 if n 1 =  µ(n)= (−1) k if n is a product of k distinct primes  0 if n is divisible by the square of a prime. 1. Let h and H be two functions from N to Z . Show that H ( n ) = )h ( d ) d|n for all n ∈ N if and only if n h ( n ) = )µ ( d ) H ( \ for all n ∈ N . d|nd 2. Show that the number I q ( n ) of monic irreducible polynomials over F q of degree n is given by I ( n ) 1) q =n d|n µ(d)q n/d. 2861 1. Explain why the binary communication channel shown in Fig. 2.3, where p 0 . 5, is called a useless channel . 2862 2. Suppose that codewords from the binary code {000 , 100 , 111} are being sent over a BSC (binary symmetric channel) with crossover probability p = 0 . 03. Use the maximum likelihood decoding rule to decode the following received words: (a) 010, (b) 011, (c) 001. 2863 3. Consider a memoryless binary channel with channel probabilities P (0 received | 0 sent) = 0 . 7 , P (1 received | 1 sent) = 0 . 8 . If codewords from the binary code {000 , 100 , 111} are being sent over this channel, use the maximum likelihood decoding rule to decode the following received words: (a) 010, (b) 011, (c) 001. 2864 4. 1. Let C = {001 , 011} be a binary code. Suppose we have a memoryless binary channel with the following probabilities: P (0 received | 0 sent) = 0 . 1 and P (1 received | 1 sent) = 0 . 5 . Use the maximum likelihood decoding rule to decode the received word 000. 2. Use the nearest neighbour decoding rule to decode 000. 2865 For the binary code C = {01101 , 00011 , 10110 , 11000}, use the nearest neighbour decoding rule to decode the following received words: 1. 2866 00000, (b) 01111, (c) 10110, (d) 10011, (e) 11011. For the ternary code C = {00122 , 12201 , 20110 , 22000}, use the nearest neighbour decoding rule to decode the following received words: 1. 01122, (b) 10021, (c) 22022, (d) 20120. 2867 7. Construct the IMLD (incomplete maximum likelihood decoding) table for each of the following binary codes: (a) C = {101 , 111 , 011}, (b) C = {000 , 001 , 010 , 011}. 8. 2868 Determine the number of binary codes with parameters ( n , 2 , n ) for n ≥ 2. Design a channel coding scheme to detect two or less errors for the message source {00 , 10 , 01 , 11}. Can you find one of the best schemes in terms of information transmission speed? 2869 3. Design a channel coding scheme to detect one error for the message source {000 , 100 , 010 , 001 , 110 , 101 , 011 , 111} . Can you find one of the best schemes in terms of information transmission speed? 2870 A multinational army has a tank corps. Each tank requires a crew of two who speak a common language. Each possible crew member generally speaks more than one language. How might the problem of maximising the number of crews be reduced to the problem of finding a maximum-cardinality matching for a graph in which each vertex represents a possible crew member? 2871 2. A theatrical agent receives offers of employment for some of his actors from a number of theatrical impresarios. Each impresario wishes to employ just one actor and, in an attempt to best meet his requirements, he offers different rates of pay for the actors he is offered. How might the problem of maximising the agent's income (if he receives a fixed percentage of his actors' incomes) be reduced to the problem of finding a maximum-weight matching for a graph in which each vertex represents either an actor or an impresario? 2872 2. The following is a statement of Hall's1•1 theorem. If G = (V, E) is a bipartite graph with bipartition (V', V"'), then G has a complete matching of V' onto V" if and only if: jN(Vi)I ;;i, Iv:1. for all v: s; V' where N(VD is the set of vertices adjacent to v:. Obtain Hall's theorem from theorem 5.2. (Suppose that IVI is even. We can construct G* by adding to G an edge joining every pair of vertices in V... Show that G has a matching, with every vertex of V' an end-point of an element of the matching, if and only if G* has a perfect matching. Hall's theorem then follows naturally. For IVI odd, a simple modification to the proof is required.) 2873 2.Job assignments An employer wishes to fill i vacancies with pretrained skilled labour. An employment agency provides a list of j potential employees, each having been trained for one or more of the vacancies. Using Hall's theorem (exercise 5.3) how might the prospects of: 1. filling all the vacancies, and 2. employing all the candidates, be judged? Does Hall's theorem provide an efficient way to answer these questions? How might a maximum number of vacancies be filled in polynomial time? 2874 The marriage problem Ina certain community every boy knows exactly k girls and every girl knows exactly k boys. Show that every boy can marry a girl he knows and vice versa. (Construct a k-regular bipartite graph in which each edge signifies that a boy (represented by one end-point) knows a girl (represented by the other end-point). The problem then reduces to showing that any k regular bipartite graph, k > 0, has a perfect matching. Show that the number of boys must equal the number of girls and that the graph satisfies Hall's theorem (exercise 5.3). The result then follows.) 2875 G = (V, E) is any 3-regular graph without cut-edges. Let G, = (Vi, E,), i = 1, 2, ..., k be the odd components (see theorem 5.2) of (G- V'), V' c: V.If m, is the number of edges with one end-point in G,and the other in V',show that m, is odd and that ;;;,, 3. Justify the following: 1k 3 = ib(G- V') = k -l: m, " !l: d(v) IV'I i-1 1'EY' thus proving, by theorem 5.2, that G has a perfect matching. 2876 Shortest time scheduling for twoprocessors A complicated task can be broken down into a number of subtasks, s" i = 1, 2, ..., n, each requiring a unit of processing time. Two processors are available and can operate simultaneously. There exists a partial ordering ' ' for the s,, such that s, s 1 means that s, must be completed before s 1• G is a digraph in which each vertex represents some s, and there is an edge (s,, s set as G and (s,, s 1) for each relation s, s 1• An undirected graph G* = (V, E*) is constructed as follows. G* has the same vertex 1) e E* if and only if there is no directed path from s, to s 1 or from s 1 to s, in G. Such a construction is shown below. Justify the statement that if M is a maximum-cardinality matching in G*, then a lower bound in the computation time for the overall task is given by (n-lMI). (Such a matching for the problem is said to be feasible if it describes a possible scheduling sequence. For example, matching { ( si. sJ , ( s 1 , s a ) } describes a feasible schedule: ( s 1 and sJ being executed simultaneously, followed by ( s 1 and s , ), and finally s 1 is executed. However, the matching {(si. sJ , (s 1 , s 1 )} is not feasible. Fujii et a1.no1 have shown that a feasible matching always exists which is of maximum cardinality and that this can be found in O(n8)-time. See also Coffman & Graham.[111) 2877 The stable marriages problem In a community of n men and n women each person ranks those of the opposite sex according to his or her preference for a marriage partner. The problem is to marry oft' all members of the community in such a way that the set of marriages is stable. The set is unstable if a man and a woman exist who are not married to each other but prefer each other to their actual mates. Gale & Shapley11 1 1have described the following algorithm to solve the problem: To start, let each boy propose to his favourite girl. Each girl who receives more than one proposal rejects all but her favourite from amongst those who have proposed to her. However, she does not accept him yet, but keeps him on a string to allow for the possibility that someone better may come along later. We are now ready for the second stage. Those boys who were rejected now propose to their second choices. Each girl receiving proposals chooses her favourite from the group consisting of the new proposers and the boy on her string, ifany. Sherejects all the rest and again keeps the favourite in suspense. We proceed in the same manner. Those who are rejected at the second stage propose to their next choices, and the girls again reject all but the best proposal they have had so far. Eventually ...every girl will have received a proposal, for as long as any girl has not been proposed to there will be rejections and new proposals, but since no boy can propose to the same girl more than once, every girl is sure to get a proposal in due time. As soon as the last girl gets her proposal the 'courtship' is declared over, and each girl is now required to accept the boy on her string. Provide brief justification for the following claims: 1. The algorithm provides a stable set of marriages. 2. The algorithm also works if the number of males does not equal the number of females. 3. The algorithm has complexity O(n 1 ). 4. The algorithm rejects men only from women that they could not possibly be married to under any stable matching. That is, that any man is at least as well-off as he would be under any other stable marriage. The algorithm is callifd man-optimal for this reason. A woman-optimal set of marriages is, of course, obtained by getting the women to propose to the men. 2878 By simplifying the algorithm described in section 5.3, produce a maximum-weight matching algorithm specifically for bipartite graphs. 2879 9. A covering C is any set of edges such that any vertex of the graph is an end-point of (at least) one edge of C. A minimum-cardinality covering is a covering with the smallest possible number of edges. 1. A salesman ineducational toys has a selection of geometrical shapes (cubes, pyramids and so on), each of which is manufactured in a range of colours. He wishes tocarry with him a minimum number of objects so that each colour and each shape is represented at least QDce. Justify the following statement. The number of objects he must carry isequal to the number of elements in a minimum-cardinality covering in the graph where each shape and each colour are individually represented by a single vertex and there is an edge joining a shape vertex to a colour vertex if that shape is manufactured in that colour. 1.Let M be a maximum cardinality matching and C be a minimum cardinality covering of G = (V, E). Now construct: 1. a covering C' from M by adding to M, for every unmatched vertex v, one edge incident with v, and 2. a matching M' from C by removing from C,for every overcovered vertex v (that is, v is the end-point of more than one edge of C) all but one edge incident with C. Show that: IC'I = IVI-IMI and that IM'I = IVI-ICI Hence deduce that C' is a minimum-cardinality covering and that M' is a maximum-cardinality matching. Thus the problem of finding a minimumcardinality covering can be solved essentially by the maximum-cardinality matching algorithm of section 5.2. 2880 6. Given a polynomial time algorithm to factorise an integer N, in unary representation, show that this does notimply that a polynomial time algorithm exists to factorise N in binary representation. (Simply show that the length of N in a unary representation is expo nential in terms of its length in binary representation.) 2881 6. Let an arbitrary decision problem D, be: Given an instance I of the problem, is A true for I? The complementary decision problem, D', is then: Given I is A false for I? Show that if Dis a member of P then so is D'. In contrast show that if D is a member of NP then we cannot necessarily draw the conclusion that D 0 e NP. (If D e P then a DTM exists for D which halts within polynomial time for all I. D' can then be solved by the sameDTM by simply inter changing the states q, and q a. On the other hand consider the case where D 0 is the problem: Is it true that there does not exist a travelling salesman's tour of length oi;. k? ) 2882 Justify the lemmas 8.1-8.S. For lemma 8.3, exercise 7.9 may be of assistance. 2883 6. Show that the following problem is NPC: Subgraph Isomorphism (SI) Instance: Two graphs G Question: Does G 1 and G 1 • 1 contain a subgraph isomorphic to G 1 ? (Consider the case that G 1 is a complete graph. In other words show thatCLIQUE cc SJ.) 2884 6. Show that the following problem is NPC: Bounded degree IIJIIIIIDing-tr (BDST) Instance: A graph G and an integer k. Question: Does G contain a spanning-tree for which no vertex has degree k? (Consider the case k = 2. In other words show that HP cc BDST.) 2885 6. In chapter 1 we saw that the problem of finding the shortest path between two vertices in a graph can be solved in polynomial time. Show, in contrast, that the following problem is NPC: Longest Path (LP) Instance: A graph G with two distinguished vertices u and o, and an integer k, 1 oi;. k n. Question: Does G contain a simple path from u to o of length k? (Show that HP cc LP.) 6. v In analogy with lemma 8.1let 1( Va v, be shorthand for Justify the claim that in a 4-vertex-colouring of g' using the colour set {O, 1, 2, 3}, v, must be coloured O if and only if all of vt, v 1 and v, are coloured O. Use g' in a proof, similar to that for theorem 8.10, that 4C is NPC. Notice that if we restrict 4C to planar graphs then, in view of the Appel-Haken proof of the four-colour coajecture, the problem is in P. 2886 6. Consider the following problem: Minimum Tardiness Seqaenclng (MTS) Instance: A set of tasks T = {ti, t 1 , ..., t,.} each requiring one unit of execution time, a set of deadlines D = {d(ti),d(t;), ..., d(t,.)}, a partial order T and an integer K, O K E;; ITI, Question: Isthere a schedule (i.e.,an order of execution of the ti) such that if t, t 1 then t, is executed before t 1 and such that no more than K tasks are completed after their deadlines? Given an instance of CLIQUE, I, we can construct an instance F(I ) of MTS. Let I consist of G = (V, E) and an integer L. F(I ) then con sists of: T = {11:i, "ii, ..., v., e v, r > 1 , e 1 , ..., ei}, v, e V and e 1 e E 1 if in G, v, is an end-point of e 1 d( vi ) = !L( L+ 1), d( e , ) = IVI+ IE l K = IEl-(!L(L-1)) This construction can clearly be carriei.r out in polynomial time. Show that /has a clique of si7.e L ifand only if F(I)has no more than K tasks completed after their deadlines. This will prove that MTS is NPC. (The partial order requires that in every schedule any 'edge' task is com pleted after its own 'endpoint' tasks. The deadlines are such that only 'edge' tasks can be late. Ifthe answer to MTS for F(I) is 'yes', then at least !L(L- 2) of these tasks must be completed before their deadline, tL(L+2). In order that the schedule does not violate the partial ordering, the corresponding 'vertex' tasks must also beexecuted before this deadline. The minimum possible number of these is L (when the corresponding vertices in G form a clique) so that the total number-of tasks now performed before the time !L(L+ 1) is tL(L-l)+L = tL(L+l) This just exhausts the available time before the 'edge'-task deadline.) 2887 8.lS. Let A(G) denote the number of vertices that an arbitrary approximation algorithm A assigns to a maximum independent set for the graph G. We denote by OPT(G) the exact number in this set. Show that if NP ¢ P, then the proposition that for all instances G that: IA(G)-OPT(G)I ... K for some integer constant K, is false. (Suppose that the proposition is true. Given G we can apply A to the (disconnected) graph G' which consists of(K +1) copies of G. Then IA(G')-OPT(G')I :!lo K and clearly OPT(G') = (K +1) OPT(G'). This also defines an algorithm B which assigns at least f A ( G ' ) / ( K +1)1 vertices to the maximum independent set of G -obtained by finding the largest set of vertices that A assigns to any of the components of G'. It follows that: IB(G)-OPT(G)I .s. K/(K+1) In other words, B(G) must be equal to OPT(G) so that B would 11e an exact algorithm. With theorem 8.4 this provides a contradiction.) 2888 In order to solve a problem Q , we have one hour of computing time on a machine which operates at 2 1 0 steps per second. Suppose that 1. two algorithms are available for Q: A 1 of complexity and A 1 of com plexity 2•, where nis the problem si7.e. Show that for any problem size, n ( > 1 ), A 1 is more efficient than A 1 for problems that can besolved within the available time. What is the maximum problem si7.e that can be handled by each algorithm within an hour? Above what value of n is A 1more efficient than A 1 ? ('There are -2 11 computational steps available in an hour.) 2. 2889 Show that the following problems (defined in the text) are in NP: vertex-cover (VC) directed Hamiltonian path (DHP) 3-colouring (3C) and show that the transformations: 3SAT cc VC (theorem 8.3) VC cc DHP (theorem 8.6) and 3SAT cc 3C (theorem 8.10) are indeed polynomial. 2890 3. Prove that MDS is NPC: Minimum dominating set (MDS) Instance: A graph G and an integer k. Question: Does G contain a dominating set of size :E;; k? (It is easy to show that VC cc MDS. Let G' and k be an instance of VC, then an instance of MDS consists of G(constructed from G' by adding, for every edge e, = (u, v) e G', a new vertex x, and edges (u, xj), (x,, v)) and k.) 2891 4. Show (directly) that CLIQUE cc IS cc VC where the problems CLIQUE, IS and YC are defined in the text. 2892 (a) Show that the DTM of figure 8.1\1\lllUld verify that M divides N in p(N) computational steps (i.e., movements of the tape head) where: p(N) = (M l) NB+ ((M 2)') N-1 = OC.N•) 2. Redesign the quintuple set of figure 8.1so that the same problem is solved but on an input tape which is the same as that shown in the diagram except that the tape cells containing A and Bare blank. That is, remove A and B from T and model the original computation with the introduction of some new states and a modification of the quintuple set. This need not affect p(N). 2. Show that the NDTM of figure 8.2 solves a problem that is in P. 2893 6. Suppose that no efficient algorithm is known for the decision problem Q, but that Q e NP. Show that an exponential-time deterministic algorithm exists for Q. (Let the NDTM which verifies Q in time p(n) be changed into a DTM which checks all possible guesses in series. The time required for this DTM is of order p(n)ITl 111ttl where T is the set of tape symbols.) 2894 1. Show that any graph with n vertices and at least r!n'l edges contains a triangle. (Use theorem 7.4.) 2895 2. In a group of eight people one person knows three others, two know· four others, three know six others, while the remaining two each know two others. Show that there must be a group of three mutual acquaintances. (Use theorem 7.4.) 2896 3. A national radio service transmits to a population residing in townships distributed throughout the country. Each town is within radio trans mission distance of at least one other. If radio transmitters are to be located in the towns, the problem of economically siting them is one of finding a minimal dominating set. For purposes of reliability, however, the engineers wish to have two sets of transmitters, each set being operated as a unit. If one unit breaks down, then the whole population is still to be serviced by the second unit. Show that this can be done within the constraint that no two transmitters are located in any one township and that it may not be necessary to have a transmitter in every town. (The problem is equivalent to showing that in every connected graph there are two disjoint minimal dominating sets. If V is the vertex-set and X is a minimal dominating set, show that ( V - X ) is a (not neces sarily minimal) dominating set.) 2897 4. P is a complete m-partite graph with n vertices. r...... is the complete m-partite graph with nvertices in which the numbers of vertices in each part are as equal as possible. Show that: IE(P)I IE(T.,....)I and that ifequality holds then Pand T,.,, .are isomorphic. (The number of vertices in any part of T ... . other part. This is not true for Pif T.,. , ..and P arenot isomorphic. Show then that IE(P)I < IE(T.,.,JI.) 11 differs by no morethan one from the number in any 2898 1.S. A Latin square is an N x N matrix in which the entries are integers in the range 1-N. No entry appears more than once in any row or any column. Justify the following construction of a Latin square, T. Form a complete bipartite graph G, each part having N vertices. Properly edgo,colour G (note theorem 7.S) using a minimum number of colours. In such a colouring associate the edge-colours of G = (V, E) with the column indices of T and associate the indices of the vertices in one part of G (let these be V 1 and let V. = V- VJ with the row indices of T. Then T(i,J) is assigned the index of the vertex we arrive at in V 1 by following the edge coloured J from the ith vertex in V 1 • 2899 6. There are 2N contestants in a chess tournament. No contestant plays more than one match in a day and must, inthecourseof thetournament, play every other player. Justify the following scheme to complete the tournament in (2N-1) days. Properly colour the edges (note theorem 7.(i) of the complete graph Ku using a minimum number of colours. Label the colours 1-(2N-1). Let the vertices of Ku represent the players. On the ith day those players connected by edges coloured i are drawn together. 2900 6. Describe. in a style similar to that used for algorithmic description throughout this text, a polynomial time algorithm to properly edge colour a graph using at most (note the proof of theorem 7.7) a+ 1 colours, where A is the maximum degree of any vertex of the graph. Make the ipplementation as efficient as you can. 2901 6. Modify the sequential colouring algorithm of figure 7.5 so that it interchanges two colours C, and C 1 in any two-coloured subgraph of the coloured portion of the graph if doing so will avoid the use of a new colour for the next vertex 111: to be coloured. This will be the case if each neighbour of 111: which is coloured C, does not belong to a same com ponent of the Kempe subgraph H(C,,C 1) as any neighbour of 1111 which is coloured C 1• 1. Show that the modified algorithm will produce a proper two colouring for any bipartite graph irrespective of the order in which vertices ·are coloured. 2. Show that the modified algorithm can utilise, for particular colouring sequences, up to k colours for graphsG' = (V',E') where V' = {u , , 11 , , w,11 E. i ,.;; k } , E'= { ( u , ,111 ) , ( u,, w 1) , ( 11 , , w 1)1i # J } and k > 3. Notice that tJ.G') = 3 and hence, as for the unmodified algorithm, the performance ratio can be arbitrarily large. 2902 6. Pror,e the following lemma due to Isaadlll G = ( V, E) is a 3-regular graph with a proper 3-edge-colouring. V' is any subset of vertices and E' is the set of edges connecting vertices in V' to vertices in ( V- V'). H the number ot ledges coloured i in E' is K,, i = 1, 2, 3, then the K, are either all evel'1 or are all odd. (Consider the components of H(C,, C 1) all of which are circuits.) 2903 6.Show (by example) that the following algorithm to find an approxi mation I to a maximum independent set / 0 has an arbitrarily large performance ratio (l ol/l I). 1. ] +- {21 2. for i = lto n do 2. If "' is not adjacent to any r, e I 2. then I +- I U {11,} Demonstrate that the performance of the algorithm is highly sensitive to the order in which the vertices are labelled. 2904 6. Use the proof of the five-colour theorem, theorem 7.11, to construct a polynomial time algorithm to properly 5-vertex-colour any planar graph. The complexity of your algorithm will probably be quadratic, however note the paper of Chiba et al.P•i 2905 6. (a) Show that a planar graph G has a 2-face-colouring if and only if G is Eulerian. (Show that the dual of G is bipartite and that any bipartite graph has an Eulerian dual.) (b) Show that every planar Hamiltonian graph has a 4-face-colouring. (Any Hamiltonian circuit divides the plane into two regions. Consider using two colours for the faces in either region.) 2906 6. N committee members sit at a round table. K different organisations have representatives on the committee. How many ways can the members be seated subject to the constraint that each organisation has a varying membership of at least one representative and when it has more than one then no two of them may sit next to each other? (The answer is provided by the chromatic polynomial of the circuit of length n, C,.: PB{C..) = (k-1)"+(-l)"(k-1)) 2907 6. Show that the following two statements are equivalent: 1. Every simple planar graph is 4-face-colourable. 2. Every simple 3-regular, 2-edge-connected planar graph is 3-edge· colourable. (Show that (a) implies (b) as follows. I.et G be a simple cubic, 2-edge connected planar graph. According to (a) it has a 4-face-colouring, let such a colouring use the colours A, B, C and D. Assign the colours a, P and 'Y to the edges as follows: a if the edge separates faces coloured (A and B) or ( C and D) P if the edge separates faces coloured (A and C) or (Band D) 'Y if the edge separates faces coloured (A and D) or (B and C) This is easily seen to be a proper 3-edge-colouring of G. Show that (b) implies (a) as follows. An equivalent statement to (a) is that any plane triangulation is 4-vertex-colourable. But any simple planar graph with triangular faces is the dual of some cubic, 2-edge connected graph. We need. therefore, only show that (b) implies that any cubic, 2-edge-connected graph is 4-face-colourable. I.et G be such a graph with a 3-edge-colouring using colours a, /J and 'Y· The two coloured subgraph H(a, /J) of G is 2-regular and so (see 7.12(a)) has a 2-face-colouring using colours a and b, say. Similarly, H(a, r) has a 2-face-colouring using colours c and d. Each face of G lies within a face of H(a, /J) and a face of H(a, r) and can therefore be assigned a pair of indices, namely (a or b) and (b or d). In fact, each face of G is an inter section of a face of H(a, /J) and a face of H(a,r)so that any two adjacent faces of G differ in at least one index. Thus the following assignments provide a proper 4-face-colouring using colours 1, 2, 3 and 4. ==== 1 (a, c), 2 (a, d), 3 (b, c), 4 (b, d)). A proper 3-edge-colouring of a cubic graph is ca11ed a Tait colouring.In 1880 Tait gave a proof of the four-colour conjecture for planar maps on the assumption that e:very cubic 2-edge-connected planar graph is Hamiltonian. However, in 1946 Tutte showed that this was an invalid assumption by constructing the nonHamiltonian cubic 3-connected graph shown below. The Tutte graph 2908 1. Inwhat graphs is an Eulerian circuit also a Hamiltonian circuit? 2. In 1736 (theorem 6.1) Euler solved a recreational puzzle of interest to the inhabitants of K6nipberg (now Kaliningrad). Kaliningrad sits across the river Pregel with seven bridges connecting the various banks and islands of the river as shown. The problem is whether or not it is possible to follow acircular walk starting and finishing at the sameriver bank and crossing each bridge precisely once. What is the answer? 2909 3. In 1859 Sir William Hamilton sold. for 25 guineas, a puzzle to a Dublin games manufacturer. The puzzle consisted of a dodecahedron (a regular solid figure with 12 pentagonal faces and hence 20 corners) and on each corner was marked the name of some capital city. One game that could be played was to construct a world tour. This consisted of a circuit, following the edges of the dodecahedron, which visited every capital city exactly once. Trace such a Hamiltonian circuit on the projection of the dodecahedron below. 2910 4. A tournament is a digraph in which there is precisely one directed edge between any pair of vertices. Suppose that n people play in a singles tennis competition, each player meeting each of the other (n-1) competitors just once. Clearly, a tournament is a representation of the competition results in which the edge (i,j) implies that competitor i beat competitor J. Show that the competitors can always be ordered so that any competitor is immediately above a competitor he has beaten (see theorem 6.8). In general how quickly can such an ordering be found? Suppose that for an edge (i,j) there also exists a path from j to i. Comment upon the sensibility of ranking the players now in the way described. 2911 Using the proof of theorem 6.1as a basis, carefully describe the details of an algorithm of O(IEI) complexity which finds an Eulerian circuit of an undirected Eulerian graph. 2912 Determine the complexity of the algorithm described in section 6.3.2 to find all the Hamiltonian tours of a graph. Hencejustify the claim that it is inefficient. 2913 7. G = (V, E) is a bipartite graph with bipartition (Y', Y1, where I Y'I '# I Y"I· Show that there always exists a proper subset of vertices W such that: C(G- W)> W where C(G-W) is the number of components of (G- W). Therefore, in view of theorem 6.11, G cannot be Hamiltonian. 2914 8. (a) Show that the Petersen graph offigure 6.14 is not Hamiltonian. The amount of computation required to find all the Hamiltonian circuits of a graph with ten vertices using the usual algorithms will be large, so use adhoc arguments. (b) Demonstrate that the removal of any vertex from the Petersen graph yields a Hamiltonian graph. (The Petersen grapl:). is the only non-Hamiltonian graph with ten or less vertices with this property.) 2915 Show that every 3-regular graph without cut-edges, contains a 2-factor (see exercise 5.6). Notice (exercise 6.8(a)) that not every such graph is Hamiltonian. 2916 The Chinese postman problem for both non-Eulerian graphs and non Eulerian digraphs has, as indicated in the text, an efficient solution. Obtain polynomial bounds, which areas tight asyou can make them, for the execution times of the algorithms described. 2917 11. The following problem may appear in a number of guises. In essence it amounts to finding a longest circular sequence of characters (from an alphabet of m characters 1,., 1 1 , •• • , 1 ,,.) that can be formed without repeating a subsequence of n characters. Such a sequence is called a de Bruijn sequence and for m = 2 the problem is called the teleprinters problem. Since there are m" distinct subsequences, then the required sequence cannot be more than m• characters long. Does a sequence of this length exist and if so, how can it be constructed? The problem can be solved using a graph in which each edge is labelled with one of the n-character subsequences; if one edge follows another on some path of the graph then the construction is such that their labels are of possible contiguous subsequences in the required circular sequence. For example, if we denote a particular (n-1) sequence of characters by ex and if l,a. labels an edge into some vertex, then those edges labelled 1.I,., a.I., •••, a.I,. will leave that vertex. Inthe diagram below, (a) shows the general attachment of edges to any vertex which is naturally labelled ex; (b) shows the whole graph for n = m = 3. 1. Show that for all n and m the graph constructed according to the above rules is Eulerian. Moreover, show that an Eulerian circuit can be used to construct a circular sequence of lengthm" in which no subsequence of length n is repeated by taking inturn the first letter of each edge label on the circuit. (Such a sequence for (b) in the above diagram is 201200011122202212110100210.) 2. A metal disc, mounted on an axle, has its circumference divided into 256 equal segments. An electric current supplied via the axle will conduct radially through the disc to a contact which touches one of the circumferential segments. Some of thC!Segments are, however, insulated. If a contact is fixed and the disc rahltes then in some positions the contact will detect a current whilst in others it will not. Show that a set of eight contacts set adjacently along the circumference of the disc can just provide sufficient information to determine the orientation of the disc. This of course presupposes a suitable ordering of insulated and conducting segments. This problem has been of practical interest in telecommunications. 3. In terms of m and n, how quickly can you find a de Bruijn sequence 'l 2918 A major computer complex has a number of operational modes for different production work. The cost in machine down time inconverting from one mode of operation i to another J is denoted by T(i,i). In general we note that T(i,J) -:/! T(j, I). In planning a week's work schedule the operations manager notes that his installation needs to operate in each of N modes once only. He also notes that in order to minimise the total machine down time he needs to find a quickest Hamiltonian path in a digraph G whose vertices are the operational modes and whose edges have execution times T(i,J). In order to find an approximation to such a path he adopts the following sequence of heuristics: 1.He removes from G, for each pair of modes i and}, the most time costly edge of either (i,J) or U, i). The resultant graph G' still contains a Hamiltonian path. Why? Show by example that a quickest Hamiltonian path in G' may be slower than a quickest Hamiltonian path in G. 2. He determines the strongly connected components of G ' : Ci . C 1, •• • , C 1• Show thatthere isanorderingof thesecomponents: c, 1 , c,., ..., c,,, such that there is an edge directed from every vertex of c,. to every vertex of C1c provided thats > t. These aretheonly edges connecting the components. 3. He notes that each Hamiltonian path of G' must consist of a Hamiltonian path of c, 1 followed by a Hamiltonian path of C " , and so on. Justify his claim that if G' contains a number of strongly connected components then the number of Hamiltonian paths in G' will ingeneral be considerably smaller than the number in G. Hence a quickest path inG' can then be determined in much shorter time than a quickest path in G. In terms of both complexity and approximation, would you generally recommend employing these heuristics? 2919 A generalisation of (transport) networks as defined in section 4.1 is to have several sources and several sinks. Let {xi, x1 , •••} and {y 11 y 1 , •••}, respectively, be the 1. set of sources and the set of sinks of such a generalised network. If we wish to maximise the overall flow from {xi, x,, ...} to {y1, y 1 , •••} then we can still use the maximum-flow algorithm to do this. Before applying the algorithm, however, we need to modify the network. This is done by adding a new source X and a new sink Y. Edges (X, xJ , (X, x 1 ), ••• are then added from X to each original source and the edges ( yi, Y), ( y 1 , Y), .•• are added from each original sink to Y . Each additional edge is given an infinite capacity. Briefly justify the following statement. If the maximum-flow al gorithm is used to maximise the flow from X to Y,then the flow obtained is also a maximum for the original network. 2920 2. A manufacturer has two despatch points D 1 and D 1 for his goods which he sends to three market points Mi, M 1 and M 8 across the network shown below. Each edge is labelled according to the maximum fl.ow of goods it can sustain. There is a market demand tf,(M) at each of the market points as follows: tf,(MJ = 10, tf,(M 1 ) = 8, tf,(M 8) = 8 Can the network meet the demand? If a factory is sited at D 1 and another at D 1 , determine ( non-unique ) separate outputs in order tomeet the situation. (Use the construction of exercise 4.1 and maximise the network flow.) 2921 3. (a) We wish to construct, if it exists, a directed simple (not necessarily connected) graph with n vertices {v,},where each vertex v, has a specified out-degree d+(vi) and a specified in-degree d-(vi). Show that the following procedure achieves this objective. First construct a network N with the vertex-set {X, Y,ai, a bi, b 1 , ••., a,., 1 , •• . , b..} and edges (X, a,) for all i, where c(X, a,) = d+(v,) (b,, Y) for all i, where c(b,. Y) = d-(v,) (a,, b 1) for all i #:- j, where c(a,. b 1) = 1 Now maximise the flow from X to Y. Ifthe maximum flow saturates all edges from X and all edges to Y then a digraph satisfying the require ments exists. It is obtained from N by removing X and Y, and each 11, is formed by coalescinga, with b,. (b) A question related to (a) concerns the excursion problem. R families go on an excursion in S vehicles. There are fipeople in the Ith family and 111 seats in thejth vehicle. Is it possible to arrange the seating so that no two members of the same family are in the same vehicle? Describe how this question may be answered. 2922 4. A generalisation of (transport) networks as defined in section 4.1 is to associate a minimum edge capacity c(u,11) with each edge (u, 11), so that a feasible flow must satisfy: c(u, 11) =s. /(u, 11) E; c(u, 11) for all (u, 11) e E and 'T.f(u, 11) = 'T./(11, u) for all 11 e Y, 11 ,f:. x,y uu 1. Iffor all (u, 11), c(u, 11) = 0 as in section 4.1, then some feasible flow exists. However, for the present generalisation a feasible flow need not exist. Construct a simple example to show this. 2. Suppose that a feasible flow F does exist for the network N. Starting from F show, as was done for the proof of theorem 4.3, that we can augment to a maximum value given by: max F(N) = min(K(P, JS)- !:... c(u, 11)). ue.r 11eP 3. Show that flow F described in (b) can be reduced to a minimum value given by: min F(N) = max ( '!:. c(u, 11)- !:..., c(u, 11)) ue,e ue.r 11eP t1eP The reduction from F is achie\lld by 'increasing' the flow along a path from the sink to the source. Such paths may be found using a labelling process, similar to that described in theorem 4.2, which starts with a labelling of the sink. 2923 19. One of the most popular uses of networks is in the scheduling of large, complicated tasks. Each edge of aPERT (Pro Evaluation and Review Technique) digraph represents a subtask and its weight is the time required to complete that subtask. Each edge (u, 11) represents a subtask which can only be started when those subtasks represented by edges incident to u have been completed. The digraph has one vertex with zero in-degree (the start vertex), and one vertex with zero out degree (the termination vertex) and every vertex is on some path from the start vertex to the termination vertex. 1. A properly constructed PERT digraph contains no directed circuits. Moreover (see (b)), it is useful to numerically label the vertices such that for every edge (u, v), u v. This labelling is called a topological sorting. Verify that the following algorithm creates a topological sorting and checks that the digraph is acyclic, Initially every vertex of the digraph N is unlabelled. 1. i +- 1 2. look for a vertex v e N with zero in-degree If no such vertex exists then goto S If such a vertex exists then begin label v with i redefine N: N +- (N-v) end 2. i +- i+ l 2. goto 2 S. if N contains no vertices then stop (the acyclic graph has a topological sorting) else stop (the graph contains a directed circuit) 1. An important parameter in any PERT digraph is the length of the longest path from the start to the termination vertex. Such a path is called a critical path, and its length represents the shortest time within which the overall task can be completed. For this reason the analysis is sometimes called CPM (Critical Path Method). Verify that, if the vertices of N are topologically sorted, then the following algorithm finds a critical path length. In fact it finds the longest path length L(i) from the start vertex to each vertex i of the network. Task U, i) takes a time w(j,i) to complete. 1. for i = 1to n do L(i) +- 0 2. Cor i = 2 to n do for all J such that U, i) e E do Lli) +- max (L(i), (L(j)+ w(j, i)) 2924 6. One version of the well-known knapsack problem is as follows. There are N items, the jth is denoted by I, and it has an integer weight w, and an integer value v,. The problem is to place a number of these items into a knapsack which can take a maximum total weight of Wand to do this so that the items in the knapsack have a maximum combined value. This problem can be transformed into one of finding a maximum-length path in a weighted acyclic network N (see the previous exercise) by the following construction. Ncontains N.(W+ l) vertices each denoted by v(i,j). The range of I is from 1 to N while J ranges from O to W. Every vertex v(i, j) has two edges incident to it, one from v((i-1),j) with zero weight and one from v((i-1), U- w,)) with weight v,, provided these vertices exist. We now add a source X and the edges (X, v(l, 0)) with zero weight and (X, v(l, w 1 )) with weight v 1 • Finally we add a sink Y and the edges (v(N,J), Y) for J = 0, 1, ..., W, all with zero weight. Prove that the set of paths from X to v(_i,j ) represents all possible subsets of {/1, / 1 , •••, IJ which have a total weight of j.Notice that one of the two edges incident to v(_i,j ) represents the absence of I, and the other represents the presence of I, in a subset. Notice also that each path length is the combined value of the represented subset. It follows that the longest path from X to Y solves this knapsack problem. 2925 6. Given the definition of pJ..v,, v 1) in section 4.3 show that if minp.(v,, v 1) occurs for two adjacent vertices u and v in an incomplete graph G, then it also occurs for two non-adjacent vertices. (Define G' = G-(u, v) and let p;(u, v) be the maximum number of vertex disjoint paths between u and v in G', then: p.(u, v) = p;(u, v) +1 Since ( u, v) ¢ G ' there exists, by theorem 4.6, a vertex-cut YC separating u from v in G ' , which has cardinality C = p; ( u, v). Now C C = n2 the n p . ( u, v) = n-1. This is not possible because G is incomplete: for any two non-adjacent vertices a and b it must be that pJ..a, b) n-2 and pJ..u, v) is supposed to be a minimum over all pairs of vertices. It follows that there exists a vertex w ¢ u or v and which is not a member of YC.Suppose, without loss of generality, that YC separates w from u (as opposed to w from v) in G'. The result then follows by observing that (YC U {v}) must separate u from w in G.) 2926 6. An employer wishes to hire, at a minimum retraining cost, n employees for different skilled work. He may choose from m candidates where m ;;;,. n. The cost of retraining candidate C, forjob a 1 is b 11• Briefly justify the following minimum-cost flow formulation of the problem. Construct a network N with the vertex-set { X , Y, Ci, c ai, a 1 , .. . , c,., 1 , •••, a.} and the edges: (X, C,) for i = 1, 2, ..., m, where c(X, CJ = 1, a( X, C,) = 0 (a 1, Y ) for J = 1 , 2, .• • , n, where c ( a'f, Y) = 1 , a( a 1, Y) = 0 ( C 1 , a 1) for all i,J where c( C , , a 1) = 1 , a( C , , a 1) = b 11 where for any edge (u, v), c(u, v) is the capacity and a(u, v) is the cost. Produce a maximum flow at minimum cost from X to Y. Employ each candidate C, for which the flow f( X, C,) = 1, and assign him for retraining to job a 1 if/ ( C , , a 1) = 1. 2927 6. 11 = min (81, 8 Suppose that in the minimum-cost flow algorithm the vertex numbers are not incremented by one but by 11defined as follows: 1 ) > 0 where 8 1 = min {(a(u, v)+1T(u)- 1T(v))l(u, v) e EJ 8 1 = min {(11'(v)-11'(u)-a(u, v))l(u, v) e E.} E 1 = { (u, v) lu e P, v e P, 1T (v) -1T (u) a( u, v ) } E. = {(u, v)lu e P, v e P, 1T(v)-1T(u) > a(u, v)} and (P, P) is the vertex-cut induced by the last application of the labelling process. Show that this modification ensures that the labelling process will label one more vertex in the next application than inthe last. Thus show that there could not be morethan n consecutive applications of the labelling process which result in no flow augmentation. 2928 6. The question: 'Does the network N contain a cut of capacity less than K?' can be answered inpolynomial time by an application of the maxi mum-flow algorithm and because of the max-flow, min-cut theorem. Suppose that N is planar. Construct a polynomial time algorithm to answer the question: • Does the network N contain a cut of capacity greater than K?' (See Hadlock.U 0 J However, if N is non-planar the problem is NP complete, see Karp.11 1 1) 2929 1. Given an arbitrary simple planar graph with n vertices and IEI edges, show that the maximum number of edges, M, that can be added to the graph, subject to it remaining planar la given by M = 3n-lEl-6 (Use Euler's formula. When no more edges can be added every face of an embedding is triangular. Every simple planar graph is thus a sub graph of such a planar triangulation.) 2930 2. Demonstrate that every simple graph with IEI planar. 2931 3. (a) Three houses have to be connected individually to the sources of three amenities (electricity, gas and water). Show that this cannot be done without at least two of the lines of supply crossing. (Because of this old problem, X.,a is sometimes known as the amenities graph.) (b) Show that the Petersen graph (figure 6.14) contains a subgraph homeomorphic to X., and is therefore, according toKuratowski's 1 theorem, non- planar. 2932 4. In a completely regular (simple planar) graph every vertex has the same degree d(v), and every face has the same degree d(f). Draw every completelyregular (finite) graph. (For thesegraphs2IEI =nd(v) =fd( f). Euler's formula then gives: n = 4d(f) '1.d(v)-d(f) (d(v)-2) For a fixed d(v) we can find the allowable d(f) consistent with a finite positive integer n. There are only five such graphs with d(v) > 2 and d(f) > 2.) 2933 In the previous exercise we presumed that n was finite. Suppose, however, that n = oo, then show that if G is completely regular and d(v) > 2 then d(f) can only be 3, 4 or 6. This is a well-known fact in crystallography. 2934 6. A self-dual is a simple planar graph which is isomorphic to its dual. Show, using Euler's formula, that if G is a self-dual then 2n = IEI +2. How might a self dual be constructed for n ,;, 4? (Not every simple planar graph with 2n = IEI +2 is a self-dual. Take care with vertices of degree 2.) 2935 6. The complement G of a graph G = (V,E) with n vertices is given by G = (K.-E). Show that if n ,;, 11, then at least one of G and {J is non-planar. (Use corollary 3.1. This result is also true for n = 9 and n = 10, but the proof is more difficult.) 2936 6. Draw a planar embedding of the following graph in which every edge is a straight line. (Every simple planar graph has an embedding in which each edge is a straight line, Fary0 7 1.) 2937 6. Show that the average degree of the vertices in a simple J)lanar graph is less than 6 (in fact less than or equal to (6-(12/n)D. Thus provide a different proof from that in the text that any simple planar graph must have at least one vertex of degree at most S. (Use corollary 3.1 and that the average degree of the vertices is 2IEl /n.) 2938 6. then G Show that if G 1 is a dual of G 1 and that if G 1 is 2-isomorphic to Gi, 1 is also a dual of G 1 • (Establish first that there is a one-to-one correspondence between edges of G 1 and edges of G 1 and that a circuit in G 1 isa circuit in G 1 and vice-versa. This cxen:ise proves one-half of theorem 3.7, proof of the other half is quite lengthy - see Whitney[lt).) 2939 6. An electrical circuit consists of connections between two sets of terminals A and B. Set A has six and set B has five terminals. Bach member of A is connected to every member of B. Show by construction that such a circuit can be printed on two sides of an insulating sheet with terminals extending through the sheet. [In general the thickness of a complete bipartite graph K••,is given by (sec the chapter by White & Lowell in I'll): T = L ic, :)-4J There may be some rare exceptions to this formula, but none has less than 48 vertices.] 2940 Find three planar graphs such that their union is the complete graph on ten vertices, K 10• 2941 2942 6. Embed the complete graph on seven vertices, K,, on a torus. 6. Describe the details of an implementation of the planarity testing algorithm of figure 3.17 which is as efficient as you can make it. Given a specific edge e of an undirected graph G, how would you construct a spanning-tree of G which contains e? How can a graph be constructed given the set of all its spanning-trees? 2943 Use theorem 2.5 to derive Cayley's theorem that the number of spanning-trees of K,. is n11-1. 2944 Theorem 2.5 provides a method to count the number of spanning out trees rooted at a particular vertex of a digraph. Contrive a similar method to count the number of spanning in-trees. 2945 4. The following algorithm due to Kruslc:allll finds a minimum-weight spanning-tree, MWT, of a weighted undirected graph G = (V, E). Show that it operates in polynomial time. 1. Relabel the elements of E so that if w(eJ > w(e 1) then i > J 2. MWT +- flJ 2. for i = 1to IEI do If MWT u {eJ is acyclic then MWT +-MWT U {e,} (Also see exercise 2.6.) 2946 5. Given a weighted undirected graph G = (V, E), let V' be a proper subset of its vertices. Also let e denote the edge of smallest weight with one end in V' and the other in (V-V'). Show that there exists a minimum-weight spanning-tree of G which contains e. (Let T be a minimum-weight spanning-tree of G. If T does not contain e, then (T+e) contains a circuit, C. Let e' ¢ ebe an edge of C. T' then defines a tree: T' = T+e-e' aearly, w(T') ._ w(T)) 64 Spanning-trees, branchings and connectivity 2947 6. Prove that Kruskal's algorithm (exercise 2.4) finds a minimum-weight spanning-tree. (Let T K be a spanning-tree constructed according to Kruskal'salgorithm and let T x be a minimum-weight spanning-tree. We assume that the edges areordered, as in exercise 2.4, according to non-decreasing weight. Change T x into T K by a series of edge replacements each as follows. If s be the smallest value of i such that e, e TK but e, ¢ T 11, construct T = Tx+e,-e; such that e; ¢ TK and e; is an edge of th circuit in (Tx+e,}. Show that T must also be a minimum-weight spanning-tree of the graph.) 2948 1. Let T be a particular spanning-tree of an undirected graph G. By c we denote a chord and by e an edge of T.Justify the following statements: 1. If S is a fundamental circuit defined by T and c, then c appears in each fundamental cut-set defined by an edge in (S-{c}) and in no others. 2. If K is a fundamental cut-set defined by T and e, then e appears in each fundamental circuit defined by a chord in K and in no others. 2949 8. Construct a polynomial time algorithm to find a set of fundamental cut-sets for some un G = (V, E). (An O(n8)-algorithm may be constructed as follows. First find a spanning-tree Tof G. Then for each edge e e Tdetermine the two blocks B 1 and B 1 of (T-{e}). The fundamental cutset associated with e, FCS(e} is then given by: FCS(e) +- fiJ for all v, e B 1 do for all v, e B, do if (v 1, v,) e E then FCS(e) +- FCS(e) U {(v,, v 1 )}) 2950 9. Construct a counterexample to show that the following 'algorithm' does not always construct a maximum branching, MB, of a weighted· digraph G :;: ( V, E). 1. Relabel the elements of E so that if w( e 1 } > w( e 1) then i > j. 2. MB+- fiJ 2. for i = 1 to IEI do if w(e;) > 0 and MB U {e,} is acyclic then MB +- MB U {e,}. 2951 10. Given a weighted directed graph, modify Edmond's algorithm to find a maximum-weight spanning out-tree if one exists. (Consider the effect of adding a constant positive weight to the existing weight of each edge of the graph.) 2952 1. Justify the following statements: 1. If G is a simple graph then 2·IEI K.(G) E. n . 2. If G is simple and 3-regular then KJ.G) = KJ.G). (Note theorem 2.9.) 2953 12. The connector problem may bemodified by insisting that certain pairs of locations be directly linked. Modify Prim's algorithm to accommodate this. (From the original weighted graph Gof the problem, construct a new graph a•,by contracting every edge thatmustappear in the solution. Consider applying Prim's algorithm to a•.) 2954 13. N(G) denotes the number of spanning-trees of the undirected graph G = ( Y, E). Show that the following recursive formula holds: N(G) = N(G-e)+N(G o e) where e e G and Go e means the graph obtained from G by contracting the edge e. Show that the implied algorithm for calculating N(G)has exponential time-complexity. (N(G-e) is the number of spanning-trees of G not using e. To every spanning-tree of G o e, there corresponds exactly one spanning-tree of G that uses e.) 2955 14. Consider again Kruskal's algorithm of exercise 2.4. We provide an outline of it once more but in the following form: 1. Construct a priority queue based on the edge-weights 2. MWT +- 0 3. Assign a 'component' number L(v) to each vertex v 4. for i = 1 to IEI do begin S.Remove the edge (u,v) of minimum weight from the priority queue 6. If L(u) '# L(v) then 6. Unite (C(u). C(v)) begin 8. MWT +- MWT U {(11, v)} end end We described priority queues in exercise 1.16. In the course of con structing MWT,the set of edges which eventually becomes theminimum weight spanningtree, MWTcontains a set of connected components each of which is a tree (initially just a single vertex). Each vertex in the same component has the same 'component' number L(v) which is different for vertices in different components. The purpose of line 7 is to make the vertices in the component C(u) which contains uand the vertices in the component C(v) which contains v,have the same component number. This could be the component number of vor of u.Notice the condition of line 6. L(u) ,:/:.L(v)shows that uis not in the same component as v. H U.u) = U.v) then MWT U {(u, v)} would contain a circuit. Fill in the implementation details which are missing from the algorithm outline and which will ensure that it runs in O(IEI log IEl) time. Notice that the use of a priority queue (exercise 1.16(a)) ensures that, for all iterations. line Srequires only O(IEI log IEl)-time. Tho remaining difficulty concerns line 7. We can see. in principle. that the total time spent executing all iterations of this instruction can be con tained within the specified limit as follows. Two components C(u) and C(v) are united into a single component by changing the component number of the vertices in the smaller component to the component number of the larger component. Consider the total number of vertex component number changes there will be. Each vertex, after changing its component number will belong to a component which is at least twice as big as its component before the change. Hence. if a vertex has its component number changed I times. it belongs to a component con taining at least 2' vertices. This cannot exceed n, so that the maximum value of i is log n. For all vertices, the total number of component number changes is therefore O(n log n). Your implementation details should ensure that this is the case. Obviously an O(IEI log IEl)-algorithm will be preferable to an O(nl)-algorithm (described in the text) for graphs with relatively few edges. 1) You are required to configure and test a DNS server. Configure a DNS server with both forward and reverse lookup. You should configure a domain name zone of .itc514.edu, and a reverse name mapping zone of 192.168.15.0/24. Configure A and PTR records for: host1 192.168.15.10, host2 - 192.168.15.11 and host3 - 192.168.15.12. Configure a CNAME of www for host1, and a CNAME of dc1 for host2. Test the operation of your DNS server using an external client running DNS queries. [10 marks] 2956 2) Create a user "assgn2' and in their home directory create the files with the following permissions [5 marks].  A file called "test.txt", with contents "This is a test file", with read and write permissions for owner, group and other, but no execute permissions.  A file called "script1" that runs a simple script of your choosing, with read and execute permissions for group and other, and full read, write and execute permissions for owner.  A hidden file called ".test_config", owned by root with contents "Test config file", that has root read, write and execute permissions only, no other permissions set.  A symbolic link with an absolute path to a system log file of your choosing.  A directory called "test_dir" with the owner having full persmissions to create, rename or delete files in the directory, list files and enter the directory. Group and other having permissions to only list files and enter the directory and access files within it. Submitt a learning diary for this activity in which you should include:  Your DNS configuration, including copies of your underlying DNS server configuration files;  Screenshots from your client device deomonstrating the operation of the DNS server;  What you did;  What problems you encountered and how you solved them;  How much time you spent on each part of the exercise. 2957 Some software vendors are developing eDirectory products, which essentially put all authentication and authorisation functions in one central repository. The central repository contains a user directory and the access control policy for all applications, such as NT network, Unix machines and databases. For this Discussion, you will consider the similarities and differences between the reference monitor concept and eDirectory products. To complete this Discussion: Post:Compare the reference monitor concept with eDirectory products. Evaluate eDirectory from a security viewpoint and from a point of view of good design. 2958 Trusted Computing Group (TCG) has developed the Trusted Computing Platform Architecture (TCPA). Programmers consider it to be a trusted computing base (TCB) development for distributed systems connected over a network. It actually provides a foundation for building and managing controlled secure environments for running applications and processing (protected) content. For this Discussion, you will review one of the articles in the UoL library that addresses trust computation in computer systems. To complete this Discussion: Post:Select and summarise any article that addresses trust computation in computer systems. Analyse how trust is used in controlling access to resources. Evaluate the proposed solution used in emergent environments such as BYOD, cloud and pervasive environments. 2959 Given unlimeted water and 4 jugs with different size, we need to get to the goal amount using A* algorithm 2960 I need this ilab done name given is to be used. 2961 Requirements Engineering Project Name. 1. Home Automation System Project work will have three phases. 1. Concept of Operations Document 2. Requirements Document 3. UML Design Document for the project Please include table of contents 2962 Create a Javascript application program for the following task: Create a webpage that contains three 2963 For this report, you are to critically evaluate and write about Air Products business processes, which are driven by well-formulated strategies that drive business value. In doing so, you will emphasise on its process management and technology by specifically focussing on processes, people, leadership, strategy, information technology, business value, and measurement as depicted in the case study and other relevant sources. For the main body of the report, you are advised to incorporatethe four part structure outlined below: Document Preview: COIT 20235/20252 BPM Case Study Report Assessment Details Term 2, 2015 Due date: 1:00 pm AEST, Wednesday, Week 12 ASSESSMENT Weighting: 55% 3 Length: 5000 words ± 10% (excluding title page, table of contents and reference list) You are required (as a group with up to four members) to write a report based on the Air Products and Chemicals Inc (Air Products) case study. Library link to case study: http://ezproxy.cqu.edu.au/login? url=http://search.ebscohost.com/login.aspx?direct=true&db=bth&AN=26452006&site=ehost-livehttp://ezproxy.cqu.edu.au/login? url=http://search.ebscohost.com/login.aspx?direct=true&db=bth&AN=26452006&site=ehost-live Reference: Air Products and Chemicals Inc 2006, Business Process Management II: Air Products Case Study, pp. 69-89, Business Source Complete, Ipswich, MA, EBSCOhost. Air Products website URL http://www.airproducts.com/http://www.airproducts.com/ For this report, you are to critically evaluate and write about Air Products business processes, which are driven by well-formulated strategies that drive business value. In doing so, you will emphasise on its process management and technology by specifically focussing on processes, people, leadership, strategy, information technology, business value, and measurement as depicted in the case study and other relevant sources. For the main body of the report, you are advised to incorporate the four part structure outlined below: Part 1: Organisational Strategy Some points to consider are: Organisational background and vision Strategy Problems faced (need for change) Process improvement road map Part 2: Process Management Some points to consider are: Process blueprint Improvement process Benefits from global processes Enablers of successful process changes Part 3: Role of Technology as a Process Enabler Some points to consider are: IT strategies Global IT structure and role Enterprise design and IT tools Measuring and monitoring processes Part 4: Change... Attach 2963 2964 You are giving the following amounts: $190,258.50; $152,698.00; $122,753.00; $220,523.00; $231,951.00. What is the average of these five amounts? 2965 I need this paper to 14-15 paper APA format. NO NO plagrism. Attach 2965 2966 I need this paper to 13-15 paper APA format . with refernces. NO NO plagrism. Attach 2966 2967 vv 2968 I need answers for all of these questions 2969 thorough executive summary and an overview of the company, its history, background, and stage in the company life cycle The need(s) the company addresses and the customers it pursues The role of the Internet in strategy: business strategy, Information Systems Strategy (IS), Information and Communication Technology Strategy (ICT), and eCommerce Strategy (EC)). Also, address the knowledge management strategies the company uses. The online user types for this company and the e-commerce considerations. Technological advantage of e-business to this company. The impact of Internet regulation to e-business companies. EC Metrics of an e-business company. EC Security of an e-business company. Limitations to Global e-commerce. 2970 all requirements Document Preview: ITECH2106-6106 Webpage & Multimedia Design CRICOS Provider No. 00103D ITECH2106-6106 Assignment 2-Design Document.docx Page 1 of 4 Assignment 2: Design Document 20 type A marks -Due week 7 – Friday 5pm Objectives This assessment task examines the following Learning Outcomes and Attributes: • Knowledge: o Recognise the importance of user analysis, content organisation, interface design, interface usability and the accessibility issues associated with multimedia and web design; o Identify, explain and apply the design principles that underlie good multimedia and webpage design, from both a visual & content design perspective. • Skills: o Demonstrate analytical skills to design quality multimedia and web pages, and efficient human-computer interaction; • Application: o Select appropriate design principles to design multimedia products and web pages that are align with project expectations; • Values: o Appreciate ethical behaviour in relation to multimedia and web page design, in particular issues related to copyright. Overview In this assignment, students are required to prepare a “Design document” which will cover most of the planning, content and design considerations of the website that they will develop in Assignment 3. The requirements of this website that you must design and develop can be found in the document “Major Assignment Overview” on Moodle. It is important that you follow the structure of the assignment on the next page when preparing the Design Document. Submission Electronic copies via Moodle. Adobe PDF or Word Doc /Docx accepted. Please refer to the “Course Description” for information regarding; late assignments, extensions, special consideration, and plagiarism. Students are reminded that all academic regulations can be accessed via the universities Website. Handbook Regulations: Publication of the handbook for students Presentation Guidelines: APA Style Presentation and Referencing Guide for Students Plagiarism Students are expected to hand in... Attach 2970 2971 deadline is in next 12 hours Document Preview: TASK 3 Specifications – Analyze SAP System-Wide Security Settings. You are required to review the system-wide security settings on our SAP system. The data file RSPARAM contains an extract from the client’s system (Note you should open this file using excel spreadsheet to view the system-wide security settings with the fields aligned correctly. Hint you can use the search function to locate the appropriate SAP system wide security settings and their related values in the data file RSPARAM.txt. You required to produce a report for Task 3 of Assignment 3 summarizing the current user settings, default settings and recommended settings based on the RSPARAM.txt file. Your report will consist of a written evaluation of the current settings highlighting any weaknesses, with explanations, and recommendations (750words approx.). Note some relevant resources on SAP security will be provided for Tutorials and Assignment 2 discussion forum. The report should take the following form: ACME DISTRIBUTION COMPANY SAP System-Wide Security Settings Date: Prepared by: System Setting Value User Default Value Recommended Value Actual Value No auto user SAP* Failed logins to end Failed logins to lock Auto failed unlock Min password length Password expiry (days) Idle logout (seconds) No check on Tcodes Default login client Attach 2971 2972 time. This "Assignment task.docx"please note that i need Plagiarism must be below 10% in TurnitinI need answer 11th september 2015 5pm melbourne Document Preview: “Length: 2000, in-text Referencing is consistently accurate and according to the APA standard. All references are cited in the text. Demonstrates breadth and depth of understanding and has insights and awareness of deeper more subtle aspects of the topic content. Evidence of having researched/read more widely beyond the core materials. Highly developed skills in expression and presentation of response. Fluent writing style appropriate to assessment task. Grammar and spelling accurate. Well-organized. Times Roman size 12 (title page and references are not counted in the 2-3 pages) that describes the business case.” Task A (10 marks): You are required in your new role as an Enterprise Architect (EA) to do a SWOT Analysis of a current ICT service in an organization. The default organization is Microsoft / Oracle, but you can substitute another known entity such as your current workplace. SWOT is an acronym for questioning the Strength, Weakness, Opportunity, Threat and helps with the analysis needed to identify the internal (S, W) and external (O, T) positives and negatives as indicated in Fig.1. Such a process can be informative and help the Enterprise Architect (you) to identify the issues and problems, set goals develop an action plan and help strategic IT Infrastructure planning and decision-making. Figure 1. SWOT analysis diagram 1. Get a copy of the 31-page SWOT Analysis Strategy Skills eBook from http://www.free-management-ebooks.com/dldebk-pdf/fme-swot-analysis.pdfhttp://www.free-management-ebooks.com/dldebk-pdf/fme-swot-analysis.pdf and note the conditions of use. Use the eBook to guide and develop your 1-2 page report summary for this task. 2. Choose a current IT service in your organization that may need updating or changing. 3. Use the following SWOT table format to develop questions that will reveal any issues or problems. 4. Identify up to a maximum of 5 Strengths, Weaknesses, Opportunities and Threats. 5. It is suggested that you use bulleted... Attach 2972 2973 This "Assignment Task 2.docx" is then main task need to be done which is highlighted as bold and related to assignment 1 which i have attached here for your reference. I need answer 9th september 2015 5pm melbourne time. Attach 2973 2974 3. Provide a list of reasons for why the response time of a client may be larger than the best-case delay. 2975 Software piracy is one of the most rampant problems plaguing the information technology space. Unfortunately, short of explicitly controlling what users do on the Internet, there is no ideal way to remedy the problem. People want as much as they can get for free, while product creators have a right to compensation for their work. One of the newer solutions to come about is the decriminalisation of piracy altogether and imposing a ‘copyright tax’. Essentially, this would be a surcharge of some sort on the use of an Internet-based service (e.g. an addition to one’s Internet bill). Through this method, copyright owners would receive compensation from these levies and free content for everyone would be provided online. Like any solution, this idea has its share of merits and detriments. For example, what if you do not pirate software? Why should you pay extra? How do you determine a fair tax and how much do copyright owners get paid? Clearly these are not the only issues argued by policy makers and Internet users; thus for this Discussion, your challenge is to further analyse the advantages and disadvantages of completely decriminalising piracy and associated copyright taxes. To complete this Discussion: Post: Create an initial post in which you evaluate the feasibility of decriminalising piracy and imposing a copyright tax. Base your evaluation on an analysis of the advantages and disadvantages of decriminalising piracy. Be sure to explain how/why such a policy would affect both Internet users and copyright owners alike. 2976 . Why is a data-sharing culture necessary in implementing the various HMIS enterprise software systems? 2977 you would be required to download promodel in order to complete this assignment.The link to download the free software ishttp://highered.mheducation.com/sites/0073401307/student_view0/promodel_software_and_tutorial.html Open the Manufacturing Cost model from the Demos subdirectory (within “Program Files\Promodel” folder on your C: drive) and run the model three different times to find out whether one,two, or three operators are optimal for minimizing the cost per part ( the cost per part is displayed on the scoreboard during the simulation). Selecting Model Parameters, you can change the number of operators from the Simulation menu by double- clicking on the first parameter ( number of operators) and entering 1,2, or 3. Then select Run from the Model Parameters dialog. Each simulation will run for 15 hours. 6. Without knowing how the model was constructed, can you give a rational explanation for the number of operators that resulted in the least cost? Attach 2977 2978 vcvcvvc 2979 Write a program that detects if there is a deadlock in the system by using a resource allocation graph. Your program should read from a file the following inputs: the number of processes and the number of resources. For each process if should read four numbers: the number of resources it is currently holding, the IDs of resources it is holding, the number of resources it is currently requesting, the IDs of resources it is requesting. The output of program should indicate if there is a deadlock in the system. In case there is, the program should print out the identities of all processes that are deadlocked. 2980 Write a Python program in which the user enters either 'A', 'B', or 'C'. If 'A' is entered, the programshould display the word 'Apple'; if 'B' is entered, it displays 'Banana'; and if 'C' is entered,it displays 'Coconut'. Use nested if statements 2981 Write a Python program in which the user enters either 'A', 'B', or 'C'. If 'A' is entered, the programshould display the word 'Apple'; if 'B' is entered, it displays 'Banana'; and if 'C' is entered,it displays 'Coconut'. Use nested if statements 2982 Write a Python program in which the user enters either 'A', 'B', or 'C'. If 'A' is entered, the program should display the word 'Apple'; if 'B' is entered, it displays 'Banana'; and if 'C' is entered,it displays 'Coconut'. Use nested if statements 2983 Write a function called maxsubsum that takes a matrix A as an input, computes the sum of elements in each of its submatrices, and finds the submatrix that has the maximum sum. (For the purposes of this exercise, we define a submatrix as a matrix formed by a contiguous set of elements of the original matrix.) If there are more than one with the same maximum sum, the function can pick any one of them. Note that the entire matrix is considered to be a submatrix of itself, but because some elements of the matrix may be negative, it may not have the maximum sum. The function is defined like this:function [row,col,numrows,numcols,summa] = maxsubsum(A)where row and col specify the indexes of the top left corner of the submatrix with the maximum sum, numrows and numcols are its dimensions, and summa is the sum of its elements. 2984 Write a function called maxsubsum that takes a matrix A as an input, computes the sum of elements in each of its submatrices, and finds the submatrix that has the maximum sum. (For the purposes of this exercise, we define a submatrix as a matrix formed by a contiguous set of elements of the original matrix.) If there are more than one with the same maximum sum, the function can pick any one of them. Note that the entire matrix is considered to be a submatrix of itself, but because some elements of the matrix may be negative, it may not have the maximum sum. The function is defined like this:function [row,col,numrows,numcols,summa] = maxsubsum(A)where row and col specify the indexes of the top left corner of the submatrix with the maximum sum, numrows and numcols are its dimensions, and summa is the sum of its elements. 2985 parent process id of a deamon process 2986 Refer from the question PPSub040815_285389_12 Please follow the outline.  As outlined in the course profile, In this group presentation you will: present   the summary of your network security plan that you have produced  identify and justify your selection of key threat or security challenge to the organization    explain what technologies will you implement to mitigate or address such threats and challenges  describe how you will test the security technologies what types of policy and/or procedure documents that you have intended to produce Ps. The presentation from PPSub040815_285389_12 solution is not match from the outline. Ps. 10 to 15 slides 2987 problem solving and 1500 words essay Attach 2987 2988 The Deep Web (Bergman, 2000), also known as the Dark Web, is a parallel Internet found only through encrypted private networks beyond the reach of search engines. Your task is to write a two-page summary (around 500 words including references) addressing the following points: 1. Describe the technical characteristics of the Dark Web ensuring you explain how it works and its underlying technologies (2.0 Marks) 1. Discuss the impact of the Dark Web on society. In addressing this point, ensure you discuss its purpose and the forces behind it (6 Marks) 1. The future of the Dark Web. How problematic will it be in years to come? What role will information security practitioners play to tackle this issue? (2 Marks) Hints: a) Use at least 4 references in your writing. b) Format your references using the Harvard reference style (Author Year). Failure to do so may result in your assignments being reported for academic misconduct. c) You may format your summary as follows: 1) Technical Characteristic of the Dark Web Your writing (100 words) 2) Impact of the Dark Web on Society Your writing (300 words) 3) The future of the Dark Web Your writing (100 words) d) Do not use a separate word document to write this summary. Use the same document to answer all questions. Just ensure that you start the summary about the Dark Web in a new page. Reference: Bergman, Michael K (July 2000).The Deep Web: Surfacing Hidden Value. BrightPlanet LLC 2989 Attached. Attach 2989 2990 additional task in assignment does not need to be done Document Preview: CRICOS Provider No. 00103D Insert file name here Page 1 of 4 ITECH3224/6224 World Wide Web Technology 2 1517/1520 Assignment 1 – "Microblog" Introduction This is an individual assignment in which you are required to develop a dynamic web application as described below using PHP, MySQL, JavaScript and CSS. Details of the weight of the assignment and due date are given in the course description. Task Description Application For this assignment, you will create a web-based microblogging platform, similar in functionality to "Twitter". You will have to come up with your own fancy name. Database Structure The web application uses a relational database to create a micro-blogging platform. The database has the following structure: User(id, name, email, password) Post(id, user_id, post_date, in_reply_to, text) Follow(user_id, follower_id) Each record in the Post table refers to a single post made by a user. Primary keys are indicated with underlines or bold formatting, and foreign keys are italicized. The following constraints should be applied in implementing the application: • The user_id and follower_id fields in the Follow table form a compound primary key, and both refer to the id field in the User table. The user id field should be an integer primary key, and should automatically increment. • The post_date field may be stored as either strings, or using MySQL datetime types, and must include time as well as date. CRICOS Provider No. 00103D ITECH3224 6224 Assignment 1 1517-1520.docx Page 2 of 4 • The text field in the Post table should be limited to 160 characters. • The in_reply_to field in the Post table is a nullable foreign key that refers to the id field on the same table. If this field is null, then the post is not a reply to another post – if it is non-null then the post is a reply to the post with the matching id. • The password field should be a VARCHAR field of at least 125 characters. The name and email fields should be VARCHAR of a length that you... Attach 2990 2991 create an application with five picturebox controls. each 2992 your company is trying to choose between purchasing the opteron and itanium2 2993 ConcurrencyProblem 1 Prove or disprove that the following schedules are serialiazable: 1. R1(x), R3(x), R1(y), R2(x), W3(x), W1(y), W3(z), R4(u), W4(u), R5(x), W5(x), W5(z) 2. R1(x), R3(x), R1(y), R2(z), W1(x), W2(y), W3(z) 3. R1(x), W1(x), R2(y), W2(y), R3(z), R4(z), R5(x), W5(x), W1(y), W1(x) Problem 2 Regardless of your answers in Problem 1, draw a timescale showing how the scheduler can introduce concurrency for each schedule to improve performance. Problem 3 A transaction manager receives the following requests in three batches: Batch 1: R1(x), R3(x), R1(y), R2(x) Batch 2: W3(x), W1(y), W3(z), R4(y) Batch 3: W4(y), R5(x), W5(x), W5(z) The transaction manager sends a batch to the scheduler at a time. Show on a timescale how the scheduler will schedule these operations, if the scheduler uses 2-phase locking. Problem 4 In problem 3, show what happens if transaction 1 decides to abort. Document Preview: CS 240—Fall 2015 Problem 1 Prove or disprove that the following schedules are serialiazable: 1. R1(x), R3(x), R1(y), R2(x), W3(x), W1(y), W3(z), R4(u), W4(u), R5(x), W5(x), W5(z) 2. R1(x), R3(x), R1(y), R2(z), W1(x), W2(y), W3(z) 3. R1(x), W1(x), R2(y), W2(y), R3(z), R4(z), R5(x), W5(x), W1(y), W1(x) Problem 2 Regardless of your answers in Problem 1, draw a timescale showing how the scheduler can introduce concurrency for each schedule to improve performance. Problem 3 A transaction manager receives the following requests in three batches: Batch 1: R1(x), R3(x), R1(y), R2(x) Batch 2: W3(x), W1(y), W3(z), R4(y) Batch 3: W4(y), R5(x), W5(x), W5(z) The transaction manager sends a batch to the scheduler at a time. Show on a timescale how the scheduler will schedule these operations, if the scheduler uses 2--phase locking. Problem 4 In problem 3, show what happens if transaction 1 decides to abort. Attach 2993 2994 Click on the following link to be taken to the course scenario: Heartland Web-Based Solutions. This is due Sept. 5 It is clear that the HWBS administration staff is a junior staff that has mostly focused on Windows servers. They are concerned that the tasks that they will need to  learn will cause a tremendous amount of unneeded stress. Describe to the staff the tasks that a Linux administrator performs.  Take this opportunity to describe the classes of administrative tasks and how they apply to the Linux environment. Adhere to MLA formatting and reference guidelines when writing your response. Additionally, your response should be free of grammatical errors, use complete sentences, and give specific details to support statements. 2–3 pages 2995 how to find capital letters in a file using pseudo code 2996 Plz tell me firstly what are protocols and thn its type i.e. Synchronous and asynchronous protocols. Further please tell me about bit oriented protocols and byte oriented protocols an its types Document Preview: HTML Web Programming Assignment In this assignment, you will design and write a small website, with a topic of your own choice, consisting of webpages using HTML code and Cascaded Style Sheets. You are to develop a basic website, which provides information in clear way and links to other pages and websites (Part A). Students are to include appropriate images, lists and tables on their pages (Part B) and to CSS functionality (Part C). Part A. You are to develop a basic website in the code and design view of Adobe Dreamweaver that enables a user to view certain website content on the webpages of this website. The user should be able to quickly understand the topic of this website. You are to show your understanding of good web design principles, such as clear hierarchy, easy navigation, and clear presentation of information. You are to demonstrate your understanding of the correct use of HTML tags. Use both the code and design view, if you are using Adobe Dreamweaver. It will be quite obvious to your tutor if you only used the design view, as it shows up in the code structure. Automatically generated code looks different from manually created HTML code. We will look for evidence that you either manually coded the webpages or that you manually corrected the code generated by Adobe Dreamweaver or a similar tool. In Part A, you are to create a main page (named index.html) and a minimum of four different subpages. These can be on the same hierarchy level or on different levels. Remember that one of the points you will be marked on is good web design and a clear hierarchy! Each page needs to have a minimum of 150 words on them. Make sure that the user can get to all of your pages via hyperlinks as well as return to previous pages via hyperlinks (rather than having to use the back button of the web browser). Also include at least one link to an external website, e.g. http://www.iqraisb.edu.au. What the tutors will be looking for the tutor’s instructions include... Attach 2996 2997 I need this paper done in 24 hrs. Attach 2997 2998 Attachments: Attach 2998 2999 I have assignment of Introduction to Information Technology, find it at the attachment. Just give me the quote please Attach 2999 3000 use matlab by using the given document which belongs to data mining Document Preview: Part I (10 marks) 1. In this part, we are going to build a decision tree classifier in MATLAB to predict the acceptability of cars. The dataset can be found in the CSV file car.csv. The first six columns are the attributes of the cars and the last column is class label denoting the evaluated car acceptability. The attribute information is shown in the following table: Attribute Description Possible values buying Buying price vhigh, high, med, low maint Maintenance price vhigh, high, med, low doors No. of doors 2, 3, 4, 5more persons Passenger capacity 2, 4, more lug_boot Size of luggage boot small, med, big safety Estimated safety of the car low, med, high accept (class label) Acceptability of the car unacc, acc, good, vgood a. All the six attributes (except the class label) require encoding (i.e. transforms them into integral values). Propose an encoding scheme, and implement it into a MATLAB function to perform the encoding. The answer should include the followings: i. Encoding scheme for each attribute (preferably presented as an encoding table) (2 marks) ii. MATLAB function source codes implementing the encoding scheme in (i) (2 marks) b. By using the first 75% of the tuples for training, and the remaining 25% for testing, build a MATLAB decision tree classifier to predict the acceptability of the cars in the testing dataset. The answer should include the followings: i. MATLAB source codes building classifier, and car acceptability prediction using the testing dataset. Clear instructions must be given for the execution of your source codes, or marks will be deducted otherwise (2 marks) ii. The decision tree built, accuracy, sensitivity, and specificity (2 marks, no marks will be given without answer for (i)) Submit your MATLAB source codes in separate MATLAB files. c. Why is the accuracy in (b.ii) much lower than sensitivity and specificity? (2 marks) Attach 3000 3001  In the Microsoft Word document you created in W2 Assignment 2, add 2–3 pages to complete the following tasks: Perform a task analysis, and write the steps needed to complete the task. You can divide a task into subtasks. Use appropriate task scenarios.  In your design, also consider the futuristic Google Glass or Microsoft Surface project and imagine how technology such as this could change your existing design. As you work on the design, you can refer to the Futuristic Technology category in the Webliography to know more about these technologies. Support your answers with appropriate examples. Cite any sources in APA format. 3002 1. Define each of the following terms: tele-care, telemedicine, tele-health, and e-health. Describe the similarities and differences between them. 2. Identify the four major types of telemedicine and provide at least one application (not in the textbook) of each type. 3. Why is the process of stakeholder analysis important? Identify and briefly describe each of the major stakeholders in globalized e-health. Your original response needs to meet a minimum of 100 words. 3003 Recently, there is strong evidence that the US National Security Agency (NSA) has launched many MiTM attacks either by exploiting some known flaws in the techniques used to protect our data or by ‘planting’ some back doors in the algorithms used to encrypt the data. It is not only the US; in some cases, such as the Flame virus, other countries engage in similar practices.In this Assignment, you will explore the leaks and news media accusing the US and other countries of launching MiTM attacks. To complete this Assignment: For this Assignment, you will write a paper on this topic. Choose one of the MiTM cases discussed in this Week’s lecture notes (the section ‘Sophisticated Attacks’) and study it. Based on your country’s laws, evaluate the legality of these actions in your own country. Express your opinion regarding your own interests to protect your assets against such exploitation. 700 - 750 words/3 references with citation 3004 A combinational circuit takes four bit input it output an odd parity bit for the input bits. For example,if input is 0001,the output and output an odd parity bit for the input is 0 as the number l's in the input string is odd; whereas for an input 0101,it output 1 3005 How long does it take to transmit a packet of size 1250 bytes over a link with capacity 1 Mbps? If the round trip time for a bit is 15msec, then what fraction of the time is the link utilized if Stop-and-Wait protocol is implemented? Can you suggest a way to increase the link utilization? I know that 1250 * 8 * 15msec = 150000msec but I am not sure what to do next 3006 Long story short, I'm president of a programming club at my university. We're all 1st and 2nd year programming students. We have a project we're about to start working on (converting a console program to a gui program, in c#). Only two of us have any experience working with winforms and event driven programming in general. We want to balance learning with production (getting the project finished) as most of us don't have time to commit to a full on, 40 hour a week project. Our adviser is trying to steer us in the direction of not using VS2010's winform designer, he's trying to make it a requirement that we code everything in a "notepad++" type environment. So basically, I need to get some answers to a few questions that I'm having trouble researching, so when we discuss how to proceed later today and tomorrow, I'm armed with some actual knowledge. (We are all, including the adviser, generally "new" to winforms,c#, and .net) In "real world" situations with winforms, how frequent is it that the designer would not at all be used? Are we (the club officers) right in our estimation that what we have figured at a 4-6 month project (using the designer) would double, if not triple coding everything without it? What are the merits of not using the designer at all as a learning tool to "see how its done"? Is it a valid learning opportunity if we use the designer, then look at the generated code to get more familiar with how our custom controls/event handlers should be done? I'm currently at a bit of a loss, and thank you all for your responses. (Also, if possible could you list your years in field, and degrees if you respond, our adviser is huge on only taking opinions from who he considers "qualified", thanks). Edit -- Also take into account that learning is also one of our priorities, not just time constraints (We're trying to strike a balance between learning every single thing that we can, and having a project that needs so much time invested in it that it becomes unfeasible for us). 3007 I have "logic engine" which executes set of user configured steps. These steps are saved in the database as "Step" entities. The engine gets the first step and then executes steps until there are no more steps to execute: public void Execute(details, data, Step firstStep) { var step = firstStep; while (null != step) { step = step.Execute(details, data); } } The different types of steps are expressed as derived classes. Each of them must implement the Execute method. The data and details parameters are used by the step to execute some logic. As fas as the logic engine knows it is just executing step after step without any knowledge what those steps do. The problem: Some of the steps need to access external services to get data or maybe even the same or different database where the actual step entities are stored. The information is usually used by other steps. One could say that some of the steps are just for loading data from external sources/database and other steps are using that data to make decisions. This separation is done so that we can use different data sources (as long as they produce the same kind of output to us) without the need to write any additional code. Is there a better way to handle this type of domain? If I separate the actual Step and the logic (i.e. loading data from external service or from database) then my whole domain model (steps) doesn't have any logic. I would most likely have something like: var handler = dictionary[step]; handler.Execute(step, details, data); Now the logic and any external dependencies are in the handler object but the actual domain object (step) is just a dummy place holder for the information. That doesn't sound right either. 3008 A logic circuit realizing the function f has four inputs A, B, C and D. The three inputs A, B, C are the binary representation of the digits 0 through 7 with A being the most-significant bit. The input D is an odd-parity bit, ie the value of D is such that A, B, C and D allways contain an odd number of 1's. (For example, the digit 1 is represented by ABC = 001 and D = 0 and the digit 3 is represented by ABCD = 0111.) The function f has value 1 if the input digit is a prime number. (A number is prime if it divisible only by itself and 1; 2 is considered to be prime but 0 and 1 are not) A list of the minterms and don't care minterms of f is : Question 23 options: f = ?m(4,7,11,14) + d(0,3,5,6,9,10,12,15) f = ?m(2,3,5,7) + d(0,1,4,6,8,9,10,11,12,14,15) f = ?m(2,3,5,7,11,13) + d(0,1,2,4,6,8,9,10,12,14,15) None of the above 3009 There is a load.txt file in which there are this information (first word is city name, the other is weight) I need to load information from this file to my program and get an array of structures and then display only the names of cities l but it doesn't work. what can be the problem? load.txt LasVegas0 200 800 0 0 LosAngeles 200 0 0 0 0 NewYprk 800 0 0 1300 0 Philladelphia 0 0 1300 0 300 Sacramento0 0 0 300 0 ------------------------------------------------///Graph.h #include using namespace std; const int MAX = 5; struct City{ char cityName[10]; int position; string weight[5]; bool mark; }; class Graph{ public: void Add(City,int); string showOneCity(int); private: City GraphList[MAX]; }; -----------------------------------------------------------------------//Graph.cpp #include #include "City.h" using namespace std; Graph::Graph() void Graph::Add(City cityInfo, int listIdx) { GraphList[listIdx] = cityInfo; } string Graph::showOneCity(int CityNum) { return GraphList[CityNum].cityName; } -------------------------------------------------------------------//test.cpp #include #include #include #include "City.h" using namespace std; const int CITIES = 5; void loadFromFile(Graph*); void showDepartureCities(Graph*); int main() { Graph grphList[CITIES]; City ctList; loadFromFile(grphList); int choice; do { cout << "\nMenu\n"; cout << "====================\n"; cout << "1.Choose departure city\n"; cout << "2.Exit\n\n"; cout << "Enter your choice: "; cin >> choice; cout << endl; switch (choice) { case 1: showDepartureCities(grphList); break; case 2: break; } } while (choice != 2); return 0; } void loadFromFile(Graph* grphList) { ifstream loadFile; loadFile.open("load.txt"); City oneCityInfo; for (int i = 0; i <= 4; i++) { oneCityInfo.position = i; loadFile >> oneCityInfo.cityName; for (int j = 0; j <= 4; j++) { loadFile >> oneCityInfo.weight[j]; } grphList[i].Add(oneCityInfo,i); } } void showDepartureCities(Graph* grphList) { for (int i = 0; i <= CITIES; i++) { cout<(); Func l = (s) => { for (int i = 0; ; i++) { var next = (s + i).TrimEnd('0'); if (!usedNames.Contains(next)) { return next; } } }; Finally I noticed I forgot to add the used name to the hash set. Similarly, I've spent minutes upon minutes over omitting context.SaveChanges(). I think I get so distracted by the details that I'm thinking about that some really small details become invisible to me - it's almost at the level of mental block. Are there tactics to prevent this? update: a side effect of asking this was fixing the error it would have for i > 9 (Thanks!) var usedNames = new HashSet(); Func name = (s) => { string result = s; if(usedNames.Contains(s)) for (int i = 1; ; result = s + i++) if (!usedNames.Contains(result)) break; usedNames.Add(result); return result; }; 3011 I have a little problem. I'm writing a resource loading and caching system, in which user can request a resource, and set a callback to be called when resource is loaded (and/or wait for load to finish). This leads to code like this: var waitobj=Loader.RequestObject("foo"); waitobj.LoadFinished+=delegate{ Bar(); }; However, since resources are cached, the call to RequestObject may actually complete synchronously. This means that when callback is set, request is already finished, and callback is never called. I thought up a clever trick: let's just check the state of request in the event adder itself! public event LoadFinishedHandler LoadFinished { add { if(Finished) value(); else m_LoadFinished+=value; } } This will call the callback function no matter what.. but my coworkers said that this method is too complicated and no one will be able to maintain this code. I like this trick anyway, but I'm obviously biased. What do you think, is this trick too clever for its own good? 3012 In linux I need to construct a message to input into linux to copy all files with the extension .txt from /home/student to /etc/config. 3013 In Linux bash script... Create a script that backs up the printed documents every 9 hours 3014 here are the link that might need for the assignment: https://sbctc-files.instructure.com/courses/1078056/files/45148695/course%20files/Chapter15/Iterator.java? download=1&inline=1&sf_verifier=ba3f1c05442c49da7b63a69529c10287&ts=1424506370&user_id=3986057 https://sbctc-files.instructure.com/courses/1078056/files/45148728/course%20files/Chapter15/Iterator.html? download=1&inline=1&sf_verifier=b7a71fc98d8a3066e1410ab15239822b&ts=1424506405&user_id=3986057 https://sbctc-files.instructure.com/courses/1078056/files/45148716/course%20files/Chapter15/IteratorJ7.html? download=1&inline=1&sf_verifier=b064df04a218ed6a2eccbe8b8091fdd6&ts=1424506420&user_id=3986057 https://sbctc-files.instructure.com/courses/1078056/files/45148727/course%20files/Chapter15/IteratorJ7css.html? download=1&inline=1&sf_verifier=a7431420203d8c2a3308fc832c9e109a&ts=1424506432&user_id=3986057 Show transcribed image text Chapter 14: Programming Project Create Javadoc for an ArraylntStack A. Create your own Stack Class, call it ArrayIntStack.java and write four public stack methods (this is the easy part of the assignment). Use at least one private helper method. All methods in your ArraylntStack must have O(constant) run-time. Your ArraylntStack uses no other Classes from the Java API. Build your own data structure here!!! 1. boolean empty(); Tests if this stack is empty. 2. int peel* Looks at the object at the top of this stack without removing it from the stack. 3. int pope; Removes the object at the top of this stack and returns that object as the value of this function. 4. int push(int item); Pushes an item onto the top of this stack. Since we're using int for return, you must throw an appropriate empty Exception for illegal peek and pop operations. B. Generate the standard Javadoc for your class (has author, date, and all methods, each with retum types plus brief descriptions) and submit just one html file : See Appendix B (Javadoc comments). Just one html file becomes the tough part of this assignment. Read on I require your Javadoc to have method summaries with information as listed (four methods) above, plus the header comments with author and date as shown by example below for the Iterator interface. CAUTION: Be certain your file submitted works by itself!!! I know it looks fine on your computer, but what will it look like when I get just that one file? Attached is a sample of the Iterator class Iteratotjava 07 from Oracle, which shows how comments are changed to produce the nice html formatted documentation in Java6 the documentation looks like: Iteratothtml ig similar to what we've been using all along. This way. the source code itself is used to generate documentation, and version control is handled really nice. You will probably need to configure your IDE to use the javadoc standard that comes with the Oracle JDK download. On my computer, the configuration path was (yours' will be slightly different): C:/Program Files (x86YJavaridkl.6.0..21/bin/javadoc.exe But then I upgraded to Java7 on a 64-bit PC, and the path to javadoc changed to C./Program FilestJavatidk1.7.0_25/biniavadoc.exe And maybe you've gone as far as Java8 now? In the Iterator example above I used Java6. If you never upgraded to Java7. you're lucky, and probably done. The rest of us have now updated' to Java7 or Java8 and it gets ugly if you're not careful, see this (BAD- >): IteratorJ7.html We have some more work to do: You must fix this ugly problem (or suffer loss of points) by either a) providing a ref to a live css page (maybe the oracle.com API pages), and then it gets back to pretty like this (GOOD->): :teratorJ7css.html fi?or b) putting your stylesheet inside the html, Option a) Find the stylesheet reference, and change it to something like: rel=stylesheer type=text/csshref=http://docs.oracle.com/javase/7/docs/api/stylesheet.css Option b) Find the stylesheet reference in you html document, rel=stylesheet' type=text/css href=stylesheetcsstitle=Style 3015 Linear Programming: Simplex Method Need help with solving this. Thank you Show transcribed image text Given the objective function: Maximize: 3x1 + 5x2 Subject to the constraints: x1+2x2 < =="" 50="" 8x1+3x2="">< =="" 240="" x1,="" x2=""> = 0 a) Solve the problem by graph method. b) Solve the problem by the Simplex Algorithm. c) With the help of MATLAB linprog, verify whether the answers you got in a) and b) are correct. 3016 Linear Optimization: What is basic variables of the point where the solution is? For example: min: 8x+4y st: 3x+4y >= 6 5x + 2y <= 10 x+4y <= 4 x >= 0 y >= 0 After finding the solution : x=2; y=0; z=16 What are the basic variables??? Thanks !! 3017 In line with this post here I am going to change my website to create a connection per query to take advantage of .NET's connection pooling. With this in mind, I don't know how I should deal with transactions. At the moment I do something like (psuedo code): GlobalTransaction = GlobalDBConnection.BeginTransaction(); try { ExecSQL("insert into table ..") ExecSQL("update some_table ..") .... GlobalTransaction.Commit(); }catch{ GlobalTransaction.Rollback(); throw; } ExecSQL would be like this: using (SqlCommand Command = GlobalDBConnection.CreateCommand()) { Command.Connection = GlobalDBConnection; Command.Transaction = GlobalTransaction; Command.CommandText = SQLStr; Command.ExecuteNonQuery(); } I'm not quite sure how to change this concept to deal with transactions if the connection is created within ExecSQL because I would want the transaction to be shared between both the insert and update routines. 3018 Like anything in life, what you don't know doesn't help you and as a new developer, I know that the more I learn about the different .NET classes out there and their uses, the more I have in my toolbox. However, sort of like an ocean where you just not sure where to start, I thought I would asked the community, does anyone know: any recommendations on breaking down a .NET library per class (or smaller), where to start? A site that might do just that per article/blog Or any other recommendations on making it a regular (i.e. daily/weekly) practice to learn a new class in .NET? Which Library to start with...etc? NOTE: I read allot or regularly, but I thought an effort geared directly at learning about a new class and its uses on a regularly bases would help. Thanks, 3019 I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels. The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n). Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g. I would like help with coming up with a pseudo-code for this setup. This is what I have so far: Edited/Updated code: XElement GetXML(ArrayList list, XElement xml) { XElement xElement = xml; // Get the rows of the current list into xmlData format ArrayList childList = GetChildList(list); if (childList != null) { foreach (Row r in list) { // Convert the rows to xml xElement = new XElement(xml); xElement.AddFirst(new XElement("Row")); xElement.Add(new XAttribute("RowId", r.RowId)); // Get the children as xml if (childList != null) { ArrayList childRows = GetChildRows(list); XElement childXml = GetXML(childRows, xElement); if (childXml != null) { xElement.Add(childXml); } } } } return xElement; } This is the main function. I can add the rest of the test program if needed. Thank you. static void Main(string[] args) { Program p = new Program(); // Initialize datasets p.InitializeLists(); // Create xml map of the datasets XElement x = p.GetXML(p.level1, new XElement("Row")); Console.WriteLine(x.ToString()); Console.ReadLine(); } 3020 Lets says I have a Carclass: public class Car { public string Engine { get; set; } public string Seat { get; set; } public string Tires { get; set; } } Lets say we're making a system about a parking lot, I'm going to use a lot of the Car class, so we make a CarCollection class, it may has a few aditionals methods like FindCarByModel: public class CarCollection { public List Cars { get; set; } public Car FindCarByModel(string model) { // code here return new Car(); } } If I'm making a class ParkingLot, what's the best practice? Option #1: public class ParkingLot { public List Cars { get; set; } //some other properties } Option #2: public class ParkingLot { public CarCollection Cars { get; set; } //some other properties } Is it even a good practice to create a ClassCollection of another Class? 3021 Lets say I receive an xml request that is sent to my web service and this request contains some data in it such as Hotel Room/Rate pairs (Room = Double Queen, Rate = 10%). The database has all of these Room/Rate pairs stored, so when the xml request comes in, I have to validate them to see if the request contains both the room and the rate in the database. If I receive one room/rate pair and it is not in the database, I fail the message and send back an error response, but if I receive 3 room/rate pairs for example, and 2 are found in the database, but one is not, I would process the succussfull ones and send back warnings for the ones that were not found. The other scenario is if I receive 3 room/rate pair and they all are not found in the database, then I want to send back an error message. What is the best way to approach these scenarios? 3022 Let's say you have a static method that looks something like this: public static bool Foo() { var bar = new Bar(); //do some stuff here } This method as it stands can be a real headache to unit test. What is the best practice to refactor this so that it can be testable, without turning it into an instance method or changing the method signature? 3023 Let's say I have a method: public void DoSomething(ISomeInterface someObject) { if(someObject == null) throw new ArgumentNullException("someObject"); someObject.DoThisOrThat(); } I've been trained to believe that throwing the ArgumentNullException is "correct" but an "Object reference not set to an instance of an object" error means I have a bug. Why? I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early. However, if I'm dereferencing it on the next line, why are we supposed to do the check? It's going to throw an exception one way or the other. Edit: It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)? 3024 Let L be a list of n items maintained according to the move-to-front heuristic. Describe a sequence of O(n) accesses that will reverse L. 3025 We learnt in class that a key indirect overhead of context switching is due to what we called A????1TLB pollution.A????1 Make sure you understand our arguments about this. It turns out that on the popular x86 processor, this overhead takes the following extreme form: the entire TLB is A????1flushedA????1 before a new address space is context switched in (i.e., all TLB entries are cleared off, say set to 0). Why do you think this is done? Should the instruction for flushing the TLB in this manner be a privileged or a non-privileged instruction? 3026 I am learning TDD using c#, as far as I know test should drive the development, that is first write a failing test after write the bare minimum code to pass the test then do refactoring. But it is also said that "Program to Interface, not Implementation", so write an interface first. This is where my confusion starts, If I am writing Interface first then it is violating two things The code that is written for interface is not driven by test. It is not the bare minimum obviously i can write it with a simple class. Should I start by writing tests for interface also ? without any implementation what am I going to test ? If this question sounds silly sorry for that, but I am utterly confused. May be I am taking things too literally. 3027 Learn from the given C program to how to print a FP representation of a real number and how to enter a FP number representation directly. a. Verify that infinity and NaN follow the format discussed in class. Specifically, identify the exponent and fraction values for each. Fraction values can be written in binary or hex. b. Modify the program to print the largest negative Single precision FP numbers in scientific notation format. c. Modify the program to print the smallest negative Single precision FP numbers in scientific notation format. d) Include the print of the program and its outputs #include #include #include main() { float f1, f2, f3; unsigned int x; double f4; f1 = 1.0; memcpy(&x, &f1, 4); printf("Floating point %f is stored as %x\n\n", f1, x); f2 = 0.0; f3 = -11.3125; memcpy(&x,&f3,4); printf("Floating point %f is stored as %x\n\n", f3, x); f3 = f1 / f2; memcpy(&x, &f3, 4); printf("The result of %f divided %f is %f stored as %x\n\n", f1, f2, f3, x); f1 = f3/f3; memcpy(&x, &f1, 4); printf("The result of %f divided by %f returns %f stored as: %x\n\n",f3, f3,f1, x); x = 0x41fd0000; memcpy(&f1, &x, 4); printf("32-bit %x has floating point value %f\n", x, f1); printf(" Printing in scientific notation: %e\n\n", f1); } 3028 You are the lead DBA for an emerging e-commerce company. Currently, you have the Standard Edition of Oracle on your server. The server is having a hard time servicing more than 5 customers at a time. Problem symptoms are things such as the server bogging down when users search for products. What would be two recommendations you could make to solve this problem? 3029 Laugh if you want, but I used to develop substantial line-of-business applications in VB6, long before the .NET framework came along. Why, when I was your age, we used to walk two miles in the snow, uphill. Both ways... Love it or hate it, VB6 had a REPL-like feel, and a very rapid development cycle. I would like to know how to come closer to that process in C#. In VB6, I could write a function, execute it, debug it and have it fully functional in a few minutes. I am told this is how the Lisp crowd works. It's a very rapid-fire style of programming. In C# I write a function, then I write a unit test for that function (which is OK, I understand the value of that), then I right-click, run test, wait for the project to compile (takes about 10 seconds right now, which would be an eternity for a REPL loop), and get an exception. Honestly, this feels more like my junior college days, when I used to feed punch cards into a hopper and wait for a printout (exaggerating only slightly for effect). Additionally, my tendency nowadays is to make everything public while I'm testing it. Unit testing with private accessors works fine, but you can't trace through the code (unless, of course, I'm doing something wrong) while you're using them. So what I'd like to know is, what adjustments have you made to your development process in C# to streamline it, and make it possible to write and verify your code very rapidly? 3030 What languge does the grammar with the following productions generated? Write the language s->aAB A->anA|lamda B->bB|b 3031 What languge does the grammar with the following productions generated? Write the language S-> AB A->bAa|ba B->Bb|lamda 3032 Language is Visual Basic Modify the Card Shuffling and Dealing Simulation (below) to present the user with a video poker hand (5 card). For the cards, each card can be any available from a standard deck of cards. Once a card is used, it cannot be used again in that hand (example: you draw the Jack of Hearts; you cannot draw that same card again). When all 5 cards are shown on screen, allow the user to discard and draw new cards once (up to all 5 cards at a time, but only allow them to change the cards once). Inform the user of their result in a dialog box (example: 3 of a kind or 2 pairs, etc.). After the user clears the result, allow the user to draw a hand again or exit the program. All programs should have basic menu options that allow the user to exit the program and perform tasks you deem necessary for the program to function correctly. After creating the program, be sure to debug and test your code. Card.vb Public Class Card Private face As String ' face of card ("Ace", "Two", ...) Private suit As String ' suit of card ("Hearts", "Diamonds", ...) ' two-argument constructor initializes card's face and suit Public Sub New(cardFace As String, cardSuit As String) face = cardFace ' initialize face of card suit = cardSuit ' initialize suit of card End Sub ' New ' return String representation of Card, Overrides defined in Ch 10 Public Overrides Function ToString() As String Return face & " of " & suit End Function ' ToString End Class ' Card DeckOfCards.vb Public Class DeckOfCards Private Const NUMBER_OF_CARDS As Integer = 52 ' number of cards Private deck(NUMBER_OF_CARDS - 1) As Card ' array of Card objects Private currentCard As Integer ' index of next Card to be dealt Private Shared randomNumbers As New Random() ' random number generator ' constructor fills deck of Cards Public Sub New() Static faces() As String = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"} Static suits() As String = {"Hearts", "Diamonds", "Clubs", "Spades"} currentCard = 0 ' set currentCard so first Card dealt is deck(0) ' populate deck array with Card objects For count = 0 To deck.GetUpperBound(0) deck(count) = New Card(faces(count Mod 13), suits(count \ 13)) Next End Sub ' New ' shuffle deck of Cards with simple one-pass algorithm Public Sub Shuffle() ' after shuffling, dealing should start at deck(0) again currentCard = 0 ' reinitialize currentCard ' for each Card, pick another random Card and swap them For first = 0 To deck.GetUpperBound(0) ' select a random number between 0 and 51 Dim second As Integer = randomNumbers.Next(NUMBER_OF_CARDS) ' swap current Card with randomly selected Card Dim temp As Card = deck(first) ' store copy of deck(first) deck(first) = deck(second) ' move deck(second) to deck(first) deck(second) = temp ' move original deck(first) to deck(second) Next End Sub ' Shuffle ' deal one Card Public Function DealCard() As Card ' determine whether Cards remain to be dealt If currentCard <= deck.GetUpperBound(0) Then Dim lastCard As Integer = currentCard ' store current card number currentCard += 1 ' increment current card number Return deck(lastCard) Else Return Nothing ' no more cards to deal End If End Function ' DealCard End Class ' DeckOfCards DeckOfCardsTest.vb Public Class DeckOfCardsTest Private deck As New DeckOfCards() ' create the deck of cards ' shuffle the deck when user clicks the Shuffle Button Private Sub shuffleButton_Click(sender As Object, e As EventArgs) Handles shuffleButton.Click deck.Shuffle() ' shuffles the deck card1PictureBox.Image = Nothing ' clear image card2PictureBox.Image = Nothing ' clear image card3PictureBox.Image = Nothing ' clear image card4PictureBox.Image = Nothing ' clear image card5PictureBox.Image = Nothing ' clear image dealButton.Enabled = True ' allow user to click the Deal Button MessageBox.Show("Deck is shuffled") End Sub ' shuffleButton_Click ' deal five cards Private Sub dealButton_Click(sender As Object, e As EventArgs) Handles dealButton.Click card1PictureBox.Image = GetCardImage(deck.DealCard()) card2PictureBox.Image = GetCardImage(deck.DealCard()) card3PictureBox.Image = GetCardImage(deck.DealCard()) card4PictureBox.Image = GetCardImage(deck.DealCard()) card5PictureBox.Image = GetCardImage(deck.DealCard()) End Sub ' dealButton_Click ' return an image for the Card argument Private Function GetCardImage(card As Card) As Image If card IsNot Nothing Then ' retrieve specific card image from resources Dim pictureResource = My.Resources.ResourceManager.GetObject( card.ToString().Replace(" ", "")) Return CType(pictureResource, Image) ' return Image Else dealButton.Enabled = False ' disable the Deal Button Return Nothing ' no more cards End If End Function ' GetCardImage End Class ' DeckOfCardsTest 3033 Language: C++ A queue is a data structure where items can only be added to the end (enqueue) and items can only be removed from the front (dequeue). A queue can easily be implemented as a linked list. Write two functions (EnQueue and DeQueue) to perform each task respectively. The node for the linked list will be very simple: an integer and a node pointer to point to the next node in the list The EnQueue function parameters will be an integer value to add to the list and a Node pointer that points to the head of the list. The DeQueue function will only have a Node pointer parameter (the head of the list). Write a driver program to test the functions. A print function may be helpful for you to see if the EnQueue and DeQueue functions are working properly. 3034 In the land of Puzzlevania, Aaron, Bob, and Charlie had an argument over which one of them was the greatest puzzler of all time. To end the argument once and for all, they agreed on a duel to the death. Aaron is a poor shooter and only hits his target with a probability of 1/3. Bob is a bit better and hits his target with a probability of 1/2. Charlie is an expert marksman and never misses. A hit means a kill and the person hit drops out of the duel. To compensate for the inequities in their marksmanship skills, it is decided that the contestants would fire in turns starting with Aaron, followed by Bob, and then by Charlie. The cycle would repeat until there was one man standing. And that man would be remembered as the greatest puzzler of all time. a. Write a function to simulate a single shot. It should use the following declaration: void shoot(bool& targetAlive, double accuracy); This would simulate someone shooting at targetAlive with the given accuracy by generating a random number between 0 and 1. If the random number is less than accuracy, then the target is hit and targetAlive should be set to false. Chapter 4 illustrates how to generate random numbers. For example, if Bob is shooting at Charlie, this could be invoked as: shoot(charlieAlive, 0.5); Here, charlieAlive is a Boolean variable that indicates if Charlie is alive. Test your function using a driver program before moving on to step b. b. An obvious strategy is for each man to shoot at the most accurate shooter still alive on the grounds that this shooter is the deadliest and has the best chance of hitting back. Write a second function named startDuel that uses the shoot function to simulate an entire duel using this strategy. It should loop until only one contestant is left, invoking the shoot function with the proper target and probability of hitting the target according to who is shooting. The function should return a variable that indicates who won the duel. c. In your main function, invoke the startDuel function 1000 times in a loop, keeping track of how many times each contestant wins. Output the probability that each contestant will win when everyone uses the strategy of shooting at the most accurate shooter left alive. d. A counterintuitive strategy is for Aaron to intentionally miss on his first shot. Thereafter, everyone uses the strategy of shooting at the most accurate shooter left alive. This strategy means that Aaron is guaranteed to live past the first round, since Bob and Charlie will fire at each other. Modify the program to accommodate this new strategy and output the probability of winning for each contestant. 3035 I have a lab problem about C++ class inheritance. In this lab, we are going to practice class inheritance. You will define a class Shape3D, which is the base class that represents three-dimensional shapes. Inside this class, there should be two pure virtual functions: virtual float get_surface_area() = 0; virtual float get_volume() = 0; These two functions must be overridden by any subclasses, returning the subclass object's surface area and volumerespectively. The Shape3D class should have the following member that represents the name of the class: std::string name; Now you need to define three subclasses, Sphere, RectangularPrism, TriangularPrism, and Cylinder whichinherit from the base class Shape3D. You should also implement a Cube class that is a subclass of theRectangularPrism. Each subclass should have member variables to represent the corresponding dimensions in order to calculate thesurface area and volume. For example, a sphere should have a radius, and a rectangular prism should have its length, width and height, etc. For the triangular prism, you can assume that it is an equilateral triangle and just calculate the base and height accordingly. You also need to define constructors for each subclass: Sphere(float radius); RectangularPrism(float length, float width, float height); TrianglularPrism(float base, float height, float sideLength); Cube(float side_length); Cylinder(float radius, float height); After implementing the classes, here is a test program that puts different shapes into a vector and print out thesurface area and volume of each shape: int main() { std::vector shapes; shapes.push_back(new RectangularPrism(8, 3, 8)); shapes.push_back(new Sphere(4)); shapes.push_back(new TriangularPrism(2,sqrt(3),6)); shapes.push_back(new Cube(4)); shapes.push_back(new Cylinder(4, 5));//SA=226.19, V=251.33 for (Shape3D* s : shapes) { std::cout << "The surface area for this "<name<<" is " << s->get_surface_area() << std::endl; std::cout << "The volume for this "<name<<" is " << s->get_volume() << std::endl; } for (Shape3D* s : shapes) { delete s; } return 0; } Note 1: DO NOT copy and paste! Note 2: When deleting a Shape3D object directly, you'll probably get a warning saying "delete called on 'Shape3D' that is abstract but has non-virtual destructor". This is because the base class Shape3D is an abstract class, so you need to define a virtual destructor: virtual ~Shape3D() {} and in each subclass, you'll need to override this virtual destructor: ~Sphere() {} ~RectangularPrism() {} ~TriangularPrism() {} ~Cube(){} ~Cylinder(){} Note 3: Some classes, such as Cube,, will have the same surface area and volume calculations as their parent classes. Therefore, all you need to do is call the super constructor from the subclass' constructor and then set the name. For example, Cube has the same surface area and volume calculations as a rectangular prism. Therefore, I would call the constructor as follows: Cube(float side):RectangularPrism(side,side,side){ name = "Cube"; } Note 4: Use this declaration to define PI: #define PI 3.14159265 Here is the example output using the above test program: ./Lab7 The surface area for this Rectangular Prism is 224 The volume for this Rectangular Prism is 192 The surface area for this Sphere is 201.062 The volume for this Sphere is 268.083 The surface area for this Triangular Prism is 39.4641 The volume for this Triangular Prism is 10.3923 The surface area for this Cube is 96 The volume for this Cube is 64 The surface area for this Cylinder is 226.195 The volume for this Cylinder is 251.327 3036 //For this lab you need to implement the convertBase10toBase class and also write a main method to test it. The convertBase10toBase method needs to be written such that the first parameter will be assumed to be in base 10 and the second will the the base to which you need to convert that first value. To generate the String return value you'll want to think about how to use the repeated division technique you saw earlier in the semester. The provided main method is just provided so that you can test your program locally before submitting. The submit server testing will only use the convertBase10toBase method itself. This two-step process will help you get a feel for thinking out an algorithm before you start writing code. import java.util.Scanner; public class ConvertNumbers { public static String convertBase10toBase(int base10val, int targetBase){ //REMOVE THE LINE OF CODE BELOW THIS COMMENT WEHN YOU IMPLEMENT THIS throw new RuntimeException("NOT YET IMPLEMENTED"); } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int decimalValue; int targetBaseValue; System.out.print("Enter a positive integer value in Base 10: "); decimalValue = sc.nextInt(); do { System.out.print("Enter a target base: "); targetBaseValue = sc.nextInt(); System.out.print(decimalValue+"(10)="); System.out.print( convertBase10toBase(decimalValue, targetBaseValue) + "("+targetBaseValue+")" ); System.out.println(); System.out.print( "Give another positive integer value in Base 10 or 0 to quit: " ); decimalValue= sc.nextInt(); } while(decimalValue!=0); sc.close(); } } 3037 I know how to write the script to generate the plot. ALthough, I need help on how to make the script identify the maximum of the curve. Using MATLAB write a program (based on Betz's Law) that will model Betz's Law. The program must produce a plot that illustrates Betz's Law. The plot must be propertly titled, axis labeled and identified. The x-axis variable must use a minimum of 100 steps (I understood this as the x-axis on the plot). The program must also identify the point at which the maximum occurs. Which should be 59% according to Betz's Law. Variables: P=Power remaining in the wind downstream of the wind turbine Po=Initial power available in the upstream wind V1=Velocity of the upstream wind V2=Velocity of the downstream wind. The plot in the assignment looks like the plot on this webpage, at the bottom. It is just the standard Betz's Law plot. http://ele.aut.ac.ir/~wind/en/stat/betzpro.htm Here is my script file: range = 0:0.01:1; %Defines the range of v total = size(range,2); for(i=1:total) v(i) = range(i); p(i) = 0.5 * ( 1-v(i)*v(i) ) * (1 + v(i)); end figure(); plot(v,p),xlabel('v_2/v_1'),ylabel('P/P_0') How can I modify this to give me the Identified Maximum? 3038 I know this worth more than 1500 points. So, I add the another question link worth 1500 point too. You can give the same answer and get 3000 points totally. 2nd question link:http://www.Transtutors.com/homework-help/questions-and-answers/hi-know-worth-1500-points-add-another-question-link-worth-1500-point-give-answer-get-3000-q6918109 files: https://www.dropbox.com/sh/q197chkff06mhl2/AABCPoHyCJ8sHje65m2MWFaHa?dl=0 links: http://www.simplistix.co.uk/presentations/python-excel.pdf http://tkinter.unpythonic.net/wiki/tkFileDialog http://effbot.org/tkinterbook/radiobutton.htm http://www.python-course.eu/tkinter_radiobuttons.php http://stackoverflow.com/questions/17757451/simple-ttk-combobox-demo https://www.daniweb.com/software-development/python/threads/350266/creating-table-in- python 3039 I know this topic has be discussed before, but I thought this might be a bit more of a detailed question... A family friend is a 12yr old boy with ADHD, and a very bright kid at that. He seems to have a solid instinct of computers, and I really think he would excel at programming. For example, today he was kicking around our place and so I opened up Visual Studio Express C#, and showed him how to create a console application (he was the one typing it all out). In about 10 - 20 minutes he was writing his own code, ReadLine()s and Writeline()s etc, and even started working on a loop. Made me think that even something like C# would definitely be within his grasp. Although Lego Mindstorms came to mind, his family isn't particularly well off and is likely not feasible. I thought about lending him one of my intro to C# books, but with the ADHD I don't know if he would have the patience to actually go through it. I also think something like Alice or Scratch would be too childish for him, and wouldn't catch his attention... I'm trying to figure out what the best way to approach this would be, and what sort of material is out there that he could teach himself how to program. Any thoughts or suggestions?? One thought I had was this book, but it may be too advanced without a basic C# background at least... Amazon C# Game Book: Thanks! 3040 I know the title of the question is very subjective, but I was confronted with usage of ?? operator by my peers, where at the same time I was not very happy/comfortable with applying var in new up-coming code. The argument given for using ?? operator was, it takes away readability in code. My question is, doesn't the same thing happens when you start using var? 3041 I know the concept of orthogonality, but from a programming language point of view, is there a way to verify/prove it? For instance in C#, one can use public or static for a method signature. You can use either or both and they wouldn't interfere with each other, so they are orthogonal to each other, right? My question is, how do I go about the rest of features, particularly features that are not related to each other? Do all the features have to coexist/stack together? Is there a programming language that is 100% orthogonal? 3042 I have a Kendo UI Grid that I am currently allowing filtering on multiple columns. I am wondering if there is a an alternative approach removing the outer switch statement? Basically I want to able to create an extension method so I can filter on a IQueryable and I want to drop the outer case statement so I don't have to switch column names. private static IQueryable FilterContactList(FilterDescriptor filter, IQueryable contactList) { switch (filter.Member) { case "Name": switch (filter.Operator) { case FilterOperator.StartsWith: contactList = contactList.Where(w => w.Firstname.StartsWith(filter.Value.ToString()) || w.Lastname.StartsWith(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).StartsWith(filter.Value.ToString())); break; case FilterOperator.Contains: contactList = contactList.Where(w => w.Firstname.Contains(filter.Value.ToString()) || w.Lastname.Contains(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).Contains( filter.Value.ToString())); break; case FilterOperator.IsEqualTo: contactList = contactList.Where(w => w.Firstname == filter.Value.ToString() || w.Lastname == filter.Value.ToString() || (w.Firstname + " " + w.Lastname) == filter.Value.ToString()); break; } break; case "Company": switch (filter.Operator) { case FilterOperator.StartsWith: contactList = contactList.Where(w => w.Company.StartsWith(filter.Value.ToString())); break; case FilterOperator.Contains: contactList = contactList.Where(w => w.Company.Contains(filter.Value.ToString())); break; case FilterOperator.IsEqualTo: contactList = contactList.Where(w => w.Company == filter.Value.ToString()); break; } break; } return contactList; } Some additional information, I am using NHibernate Linq. Also another problem is that the "Name" column on my grid is actually "Firstname" + " " + "LastName" on my contact entity. We can also assume that all filterable columns will be strings. 3043 I keep hearing that c# is "better" than vb... but as far as I can see, aside from syntactical differences, both compile down to the same IL. I've found some good articles by googling that explain what the differences are between the two and so I feel comfortable in "diffusing" conversations between developers arguing over vb / c#. =) But I did read an article that said vb.net 2005 had better support for com interop stuff. But i'm wondering if this is still the case? This is of interest to me because we are in the middle of redesigning an old vb6 app that communicates with some older COM components. Does anyone have recent experience with .NET and COM interop? Thanks. 3044 I keep getting an error "segmentation fault (core dumped)" when i try to run my code. What would I need to fix to make that error go away. #include #include #include struct _data { char *name; long number; }; int SCAN(FILE *stream){ int count = 0; char line[256]; while (fgets(line, sizeof(line), stream)) { count++; } return count; } int SEARCH(struct _data *BlackBox, char *string, int size){ int i = 0; for (i = 0; i if (strcmp(BlackBox[i].name, string) == 0) return i; } return -1; } struct _data* BlackBoxLOAD(FILE **stream, int size){ struct _data* BlackBox = (struct _data*)malloc(sizeof(struct _data)*size); int count = 0; char line[256]; while (fgets(line, sizeof(line), *stream)) { char* token = strtok(line, " "); struct _data* temp = (struct _data*)malloc(sizeof(struct _data)); temp->name = token; token = strtok(NULL, " "); temp->number = atoi(token); BlackBox[count] = *temp; count++; } return BlackBox; } void FREE(struct _data *BlackBox, int size){ free(BlackBox); return; } int main(int argc, char *argv[]) { int i = 0, size = 0; FILE *stream = fopen("hw5.data", "r"); int noOfLines = SCAN (stream); size = noOfLines; struct _data *BlackBox = BlackBoxLOAD(&stream, size); fclose(stream); for (i = 1; i if (argv[i] == "") { printf("*******************************************"); printf("* You must include a name to search for. *"); printf("*******************************************"); } int pos = SEARCH(BlackBox, argv[i], size); if (pos == -1) { printf("*******************************************"); printf("The name was NOT found."); printf("*******************************************"); } else{ printf("*******************************************"); printf("The name was found at the %d entry.", pos); printf("*******************************************"); } } FREE(BlackBox, size); } 3045 What is k(x)= 2x^3-5x^2-x+6 written in standard form and as a product of linear factors??? Thanks for help !! 3046 JK is equal to (x squared - 4x). KL is equal to (3x-2). JL=28. How do you find out what x equals??? Thanks !! 3047 JK is equal to (x squared - 4x). KL is equal to (3x-2). JL=28. How do you find out what x equals? ?? Thanks for help !! 3048 This is In JavaScript using JAvafx. Show transcribed image text This is In JavaScript using JAvafx. 1. The UI includes a. a Play button that starts the game i. The play button shuffles the cards ii. The play button becomes disabled once the game has started and there are cards remaining in the deck iii. Resets the number of wins per user b. A Deal button i. that deals the remaining cards in the deck ii. Deal button is only enabled when after the play button has been pressed AND there are cards remaining in the deck c. End game button i. When pressed, a popup appears that displays, Are you sure you want to end the game. 1. If Yes, end game and close UI 2. If No, return to game 2. The game will have 4 players. a. A card is dealt to each player. i. A visual graphic (i.e., image) of the card (see Figure 14.43c) is displayed AND the caption of the card (Ace of Spades) that corresponds to the graphic b. Once all 4 cards have been dealt, the winner must be displayed A???n a visual manner c. A running count of number of wins d. Once all cards have been dealt (i.e., 13 games) the final winner (i.e., the player who collected the most wins, must be visually displayed) Order of cards (from low to high): 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace Order of suits (from low to high): Clubs, Hearts, Diamonds, Spades 3049 JavaFX (not Swing) Write a program that displays a 10 by 10 square matrix. Each element in the matrix is 0 or 1, randomly generated. Display each number centered in a text field. Use TextField's setText method to set value 0 or 1 as a string. 3050 JAVA Write a static method named mergeMaps that takes two Maps using Strings as keys and Integers as values. The method should return a Map that uses Strings as keys and Integers as values. If the two maps passed in as parameters have no conflicts, the method should return a new Map that contains everything that is in either Map. If the two maps have a conflict, the method should return a null value. 3051 JAVA Write a static method named conflicts that takes two Maps using Strings as keys and Integers as values. The method should return a Set of Strings. The Set returned by conflicts should be a list of all of the keys that are in conflict between the two Maps. A conflict occurs when two keys point to a different value in the two different maps. (For example, map1 might have the key "Apple" pointing to the Integer 12 and map2 might have the key "Apple"pointing to the Integer 15 - the key "Apple" would need to be added to the Set of conflicts returned by the method). 3052 JAVA Write a second difference method called inPlaceDifference. This will be a void method that takes two Sets A and B as parameters and modifies the first Set A so that it contains (A-B). This method should be implemented using an Iterator to remove elements from the Set A that are also contained in Set B. 3053 This is in java. Write a program that solves the A????1KnightA????1s TourA????1 chess problem. This solution must follow the recursive backtracking. it must be 5 by 5. 3054 In Java write a program that reads the content of a file, modifies that content, and then writes the result to a new file. First, you need to decide exactly how you want to modify the content of the file, ultimately the details are up to you. There are a few restrictions. First, you need to make at least two modifications. And second, one of those modifications must be a replacement kind of modification (I recommend making use of the string method .replace()). So for example, you could replace every occurence of the letter "O" with the digit "0" and every occurence of the letter "I" with the digit "1". But it has to be something different than that example. Then write a program that uses this trasformation to alter the contents of a text file. You should include a static method that takes a string and returns the transformed version of the string. The main() method should ask the user for a source filename and a destination filename. Then it should read the content from the source file, modify it using your transformation method, and write the results to the destination file. If any IOExceptions are thrown, it should display an error message and ask the user to enter a new file. 3055 In java, Write an expression that continues to bid until the user enters 'n'. import java.util.Random; import java.util.Scanner; public class AutoBidder { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); Random randGen = new Random(); char keepGoing = '-'; int nextBid = 0; randGen.setSeed(5); while (/* Your solution goes here */) { nextBid = nextBid + (randGen.nextInt(10) + 1); System.out.println("I'll bid $" + nextBid + "!"); System.out.print("Continue bidding? "); keepGoing = scnr.next().charAt(0); } System.out.println(""); return; } } 3056 In java, Write an expression that continues to bid until the user enters 'n'. import java.util.Random; import java.util.Scanner; public class AutoBidder { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); Random randGen = new Random(); char keepGoing = '-'; int nextBid = 0; randGen.setSeed(5); while (/* Your solution goes here */) { nextBid = nextBid + (randGen.nextInt(10) + 1); System.out.println("I'll bid $" + nextBid + "!"); System.out.print("Continue bidding? "); keepGoing = scnr.next().charAt(0); } System.out.println(""); return; } } 3057 In Java, write a class Grade with following member variables and method: int midtermExam, int finalExam: represent the scores of midterm and final exams respectively. The maximum score for each exam is 100. double getOverallScore(): returns the overall score calculated as follows: 40% midterm and 60% final. Write another class Grade180 that is a subclass of Grade and has the following member variables and method: int midtermExam, int finalExam: inherited from Grade super class. int hw1, int hw2, int project1, int project2 : represent the scores of homeworks, projects respectively. The maximum score for each homework and project is 100. double getOverallScore(): overrides the method in Grade class and returns the overall score calculated as follows: 20% homeworks (each of equal weight), 30% projects (each of equal weight), 20% midterm and 30% final. Note: data for member variables should be passed as arguments to their respective constructors and initialized in them. You may use your main method for testing, but it will not be tested by webcat. 3058 In Java, Write a class BankAccount with following member variables and methods: String id, int balance: represent the account's ID, and the balance in the account. void depositMoney(int deposit): adds deposit amount to the balance. void withdrawMoney(int withdraw): subtracts withdraw amount from the balance. int getBalance(): returns the present balance in the account. You have to write your own exception class NegativeBalanceException to ensure that the balance can never go negative. An attempt to make the balance less than 0 will throw an exception with the message A????1Balance cannot be negative.A????1 Make sure you handle all possible cases where a method could make the balance negative, no matter how unlikely they seem. Please make sure, as always, that all fields, method names, class names, and Strings are copied exactly from the handout. You will turn in a zip file containing both your main class and your exception. 3059 Java Working with the server. The client works with a grade book (adding and viewing entries) by selecting a grade book listed by the server. First it must request the list from the server. Then respond with an index corresponding to the list sent by the server. The server will then use that grade book for adding and viewing entries. 3060 In JAVA, A UML diagram that helps with the process: Show transcribed image text Be sure to include the following methods: Constructor - accepts an integer argument specifying the length of the queue. enqueue Accepts a value to put in the queue. Throws an exception if the queue is full. dequeue - Returns a value from the queue. Throws an exception if the queue is empty. Is Full - Returns true if the queue is full, false otherwise. Is Empty - Returns true if the queue is empty, false otherwise. toString - Returns a string representation of the queue. You may not use the Java API queue container (Java.util.Queue). For the exception, Just throw an Exception, i.e., new Exception(Something? 3061 This is in Java. A table look-up process can shorten the time it takes to compute the function values of Ackermann by storing intermediate results in a table for Ackermann and using these values when they are available. Without a table lookup there are 693,964 calls to the function for M = 3, N = 7. As you saw when you worked by hand the values for Ack(2,1) and Ack(2,2) there were many calls to the function before it finally gave the final answer. Many of the 693,964 intermediate values of Ackermann were generated from a small set of calls that were called many times. When the Ackermann function is called with an M and N the program checks the two dimensional table to see if the return value is stored at that location. The values of M and N are the index values used to identify that particular Ackermann value. If this is the first time this M and N are called then the value in the table will be zero and the function must then determine the value for that particular M and N. If it was the first time for that set of M and N, when it is computed store the value in the array. The next time that set of M and N are called, when the table is checked for a value the value will now be there. This value is immediately returned. With the table lookup there were only 3074 calls to the function rather than 693,964. The size of the array must accommodate the values for M which are 0 A????1 3 and the values of N which will be one less than the final value of the function. If M = 3, N = 7 are used the final value is 1021. This requires a table that can store values of N to be at least 0 A????1 1020. As with the trace, print the number of times the function was called. A very safe value for N is 10,000. Memory is cheap. 3062 Java, Stacks, Grouping Symbols Matching Problem Show transcribed image text Write a Java program that reads iii an arithmetic expression front the key- Board and returns true if the expression contains matching and balanced grouping symbols amid false otherwise. Take the grouping symbols to be (, ), [, j. {, and }. For example, for the input ([[(2+3)*4] -2] +6) your program should return true, while for [(2]) your program should return false. 3063 What is the Java source filename extension? What is the Java bytecode filename extension? Write a Java statement to display the string A????1The value is 100A????1 to a user in a plain dialog box. What is the command you would use to compile the file Addition.java? What is the command you would use to execute the Addition class? What does a Java class contain that identifies it as a Java application? Write a Java statement that declares a constant called MAX which has a value of 1000. How do C++ chars differ from Java chars? Given a double variable called dval, write a single Java statement to prompt the user to enter the price of an item using JOptionPanes, convert the result and store it into dval. Write one Java statement to display the string A????1The average is xxxA????1 to the console, where the xxx displays the value from the double variable sum divided by 3. Make sure the value is displayed with 3 digits following the decimal point. Write one Java statement to create a string containing A????1The average is xxxA????1 where the xxx contains the formatted value from the double variable sum divided by 3. Make sure the formatted string contains only 2 digits following the decimal point. Store the formatted string into a String variable called str. 3064 Java: Solitaire Lab Show transcribed image text Java: Solitaire Lab Purpose The purpose of this lab is for you to work with array lists. Problem specification You will model a particular type of solitaire. The game starts with 45 cards. (They need not be playing cards. Unmarked index cards work just as well.) Randomly divide them into some number of piles of random size. For example, you might start with piles of size 20, 5, 1, 9 and 10. In each round, you take one card from each pile, forming a new pile with these cards. For example, the sample starting configuration would be transformed into piles of size 19, 4, 8, 9 and 5. The solitaire is over when the piles have size 1, 2, 3, 4, 5, 6, 7, 8, and 9, in some order. (It can be shown that you always end up with such a configuration.) 3065 Java Server Commands GetStudents: - returns a : separated list of names for currently selected course. hw: and exam: - registers a grade book entry. ListEntries: - returns one string for each entry, ends by sending EOL: AddCourse: - expects a course name after the colon. CourseList: - returns : separated list of course names SelectCourse: - expects an index number after the colon that corresponds to the CourseList. Assignment ground work The server side is provided along with some skeleton code for the client. The skeleton methods in the client are suggestions. Feel free to modify them and you will probably want to add more. 3066 In Java, Sample output: Show transcribed image text Write a program that lists the contents of a directory. The program should prompt the user for a path to a directory the user would like to view. If the directory exists, it should then display each entry in the directory (file or subdirectory). For each entry, display the path of the entry, it?s size, and it?s last modification date. In addition, indicate if the entry is a directory. Also indicate if the entry is the absolute path. Your program should match the format of the sample runs as closely as possible. A couple sample runs: D indicates the entry is a directory. A indicates the path is an actual path. 3067 In JAVA, Sample output should look like this and so forth. The 'dots' are examples of more filenames,bytes,modification dates. 3068 JAVA QUESTION: I need help adding a feature to alphabetically sort a payroll report (sorting requirement forces an array), such as, Employees: array of EmployeeRecord, other than that, everything else works. You start with a file called: InputData.txt which contains the following data: Marion Louise 13.00 40.00 442.00 Davidson Carl 8.75 38.00 282.63 Whittle Ed 11.50 25.50 249.26 Doe John 17.00 46.50 718.89 Prentiss Paula 15.75 50.50 746.35 Then, you have the working Java application named: ReadDataFile.java: package readdatafile; /** * * @author YOUR NAME */ import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static javafx.beans.binding.Bindings.concat; import java.util.*; public class ReadDataFile { public static void main(String[] args) throws IOException { Scanner sInputFile = null; String Lastname = ""; String Firstname = ""; int EmployeeCount = 0; float TAXRATE = 15; float PayRate = 0, HrsWkd = 0, GrossPay = 0, TaxAmt = 0, NetPay = 0, totPayRate = 0, totHrsWkd = 0, totGrossPay = 0, totTaxAmt = 0, totNetPay = 0; try { sInputFile = new Scanner(new BufferedReader(new FileReader("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/inputData.txt"))); File file = new File("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/Report.txt"); PrintWriter printWriter = new PrintWriter(file); printWriter.println(" ===================================================================================="); printWriter.println(" | EMPLOYEE RECORD |"); printWriter.println(" ====================================================================================\n\n"); printWriter.println(" printWriter.println(" Employee Name Pay Rate Hours Gross Tax Worked Pay Amount printWriter.println(" ==================================== while (sInputFile.hasNextLine()) { Lastname = new String(sInputFile.next()); Firstname = new String(sInputFile.next()); PayRate = sInputFile.nextFloat(); Net"); Pay"); ===== ====== ====== ====== ======"); HrsWkd = sInputFile.nextFloat(); GrossPay = sInputFile.nextFloat(); Lastname = Lastname + ", " + Firstname; TAXRATE = 15; TaxAmt = (((GrossPay - 1) * TAXRATE) / 100); NetPay = (GrossPay - TaxAmt); totPayRate += PayRate; totHrsWkd += HrsWkd; totGrossPay += GrossPay; totTaxAmt += TaxAmt; totNetPay += NetPay; EmployeeCount++; { System.out.printf(" %20s, %15s %5.2f %3.2f %7.2f\n", Lastname, Firstname, PayRate, HrsWkd, GrossPay); printWriter.printf(" %-35s %5.2f %3.2f %7.2f %7.2f %7.2f\n", Lastname, PayRate, HrsWkd, GrossPay, TaxAmt, NetPay); } } // while System.out.printf(" %5.2f %5.2f %7.2f %5.2f printWriter.printf("\n\n Totals %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %5.2f %5.2f %7.2f %5.2f %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); System.out.printf(" %3.2f %5.2f %7.2f printWriter.printf("\n Averages %3.2f %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %3.2f %5.2f %7.2f %3.2f %7.2f\n", totPayRate / EmployeeCount, totHrsWkd / EmployeeCount, totGrossPay / EmployeeCount, totTaxAmt / EmployeeCount, totNetPay / EmployeeCount); System.out.println(" Table created ... terminating application\n"); printWriter.close(); } // try catch (Exception IOException) { System.out.println("Unknown file error occurred ..."); } finally { sInputFile.close(); } } // main } // class 3069 JAVA QUESTION: I need help adding a feature to alphabetically sort, in alphabetical order, a payroll report (sorting requirement forces an array), such as, Employees: array of EmployeeRecord, other than that, everything else works. You start with a file called: InputData.txt which contains the following data: Marion Louise 13.00 40.00 442.00 Davidson Carl 8.75 38.00 282.63 Whittle Ed 11.50 25.50 249.26 Doe John 17.00 46.50 718.89 Prentiss Paula 15.75 50.50 746.35 Then, you have the working Java application named: ReadDataFile.java: package readdatafile; /** * * @author YOUR NAME */ import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static javafx.beans.binding.Bindings.concat; import java.util.*; public class ReadDataFile { public static void main(String[] args) throws IOException { Scanner sInputFile = null; String Lastname = ""; String Firstname = ""; int EmployeeCount = 0; float TAXRATE = 15; float PayRate = 0, HrsWkd = 0, GrossPay = 0, TaxAmt = 0, NetPay = 0, totPayRate = 0, totHrsWkd = 0, totGrossPay = 0, totTaxAmt = 0, totNetPay = 0; try { sInputFile = new Scanner(new BufferedReader(new FileReader("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/inputData.txt"))); File file = new File("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/Report.txt"); PrintWriter printWriter = new PrintWriter(file); printWriter.println(" ===================================================================================="); printWriter.println(" | EMPLOYEE RECORD |"); printWriter.println(" ====================================================================================\n\n"); printWriter.println(" Employee printWriter.println(" Name Pay Rate Hours Gross Tax Worked Pay Amount printWriter.println(" ==================================== Net"); Pay"); ===== ====== ====== ====== ======"); while (sInputFile.hasNextLine()) { Lastname = new String(sInputFile.next()); Firstname = new String(sInputFile.next()); PayRate = sInputFile.nextFloat(); HrsWkd = sInputFile.nextFloat(); GrossPay = sInputFile.nextFloat(); Lastname = Lastname + ", " + Firstname; TAXRATE = 15; TaxAmt = (((GrossPay - 1) * TAXRATE) / 100); NetPay = (GrossPay - TaxAmt); totPayRate += PayRate; totHrsWkd += HrsWkd; totGrossPay += GrossPay; totTaxAmt += TaxAmt; totNetPay += NetPay; EmployeeCount++; { System.out.printf(" %20s, %15s %5.2f %3.2f %7.2f\n", Lastname, Firstname, PayRate, HrsWkd, GrossPay); printWriter.printf(" %-35s } } // while %5.2f %3.2f %7.2f %7.2f %7.2f\n", Lastname, PayRate, HrsWkd, GrossPay, TaxAmt, NetPay); System.out.printf(" %5.2f %5.2f %7.2f %5.2f printWriter.printf("\n\n Totals %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %5.2f %5.2f %7.2f %5.2f %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); System.out.printf(" %3.2f %5.2f %7.2f %3.2f printWriter.printf("\n Averages %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %3.2f %5.2f %7.2f %3.2f %7.2f\n", totPayRate / EmployeeCount, totHrsWkd / EmployeeCount, totGrossPay / EmployeeCount, totTaxAmt / EmployeeCount, totNetPay / EmployeeCount); System.out.println(" Table created ... terminating application\n"); printWriter.close(); } // try catch (Exception IOException) { System.out.println("Unknown file error occurred ..."); } finally { sInputFile.close(); } } // main } // class 3070 JAVA QUESTION: I need help adding a feature to alphabetically sort, in alphabetical order, a payroll report (sorting requirement forces an array), such as, Employees: array of EmployeeRecord, other than that, everything else works. You start with a file called: InputData.txt which contains the following data: Marion Louise 13.00 40.00 442.00 Davidson Carl 8.75 38.00 282.63 Whittle Ed 11.50 25.50 249.26 Doe John 17.00 46.50 718.89 Prentiss Paula 15.75 50.50 746.35 Then, you have the working Java application named: ReadDataFile.java: package readdatafile; /** * * @author YOUR NAME */ import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static javafx.beans.binding.Bindings.concat; import java.util.*; public class ReadDataFile { public static void main(String[] args) throws IOException { Scanner sInputFile = null; String Lastname = ""; String Firstname = ""; int EmployeeCount = 0; float TAXRATE = 15; float PayRate = 0, HrsWkd = 0, GrossPay = 0, TaxAmt = 0, NetPay = 0, totPayRate = 0, totHrsWkd = 0, totGrossPay = 0, totTaxAmt = 0, totNetPay = 0; try { sInputFile = new Scanner(new BufferedReader(new FileReader("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/inputData.txt"))); File file = new File("/Volumes/KINGSTON/scc/cisp401/Assignments/project01/project/Report.txt"); PrintWriter printWriter = new PrintWriter(file); printWriter.println(" ===================================================================================="); printWriter.println(" | EMPLOYEE RECORD |"); printWriter.println(" ====================================================================================\n\n"); printWriter.println(" Employee printWriter.println(" Pay Name Rate Hours Gross Tax Worked Pay Amount printWriter.println(" ==================================== Net"); Pay"); ===== ====== ====== ====== ======"); while (sInputFile.hasNextLine()) { Lastname = new String(sInputFile.next()); Firstname = new String(sInputFile.next()); PayRate = sInputFile.nextFloat(); HrsWkd = sInputFile.nextFloat(); GrossPay = sInputFile.nextFloat(); Lastname = Lastname + ", " + Firstname; TAXRATE = 15; TaxAmt = (((GrossPay - 1) * TAXRATE) / 100); NetPay = (GrossPay - TaxAmt); totPayRate += PayRate; totHrsWkd += HrsWkd; totGrossPay += GrossPay; totTaxAmt += TaxAmt; totNetPay += NetPay; EmployeeCount++; { System.out.printf(" %20s, %15s %5.2f %3.2f %7.2f\n", Lastname, Firstname, PayRate, HrsWkd, GrossPay); printWriter.printf(" %-35s %5.2f %3.2f %7.2f %7.2f %7.2f\n", Lastname, PayRate, HrsWkd, GrossPay, TaxAmt, NetPay); } } // while System.out.printf(" %5.2f %5.2f %7.2f %5.2f printWriter.printf("\n\n Totals %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %5.2f %5.2f %7.2f %5.2f %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); System.out.printf(" %3.2f %5.2f %7.2f printWriter.printf("\n Averages %3.2f %7.2f\n", totPayRate, totHrsWkd, totGrossPay, totTaxAmt, totNetPay); " + " %3.2f %5.2f %7.2f %3.2f %7.2f\n", totPayRate / EmployeeCount, totHrsWkd / EmployeeCount, totGrossPay / EmployeeCount, totTaxAmt / EmployeeCount, totNetPay / EmployeeCount); System.out.println(" Table created ... terminating application\n"); printWriter.close(); } // try catch (Exception IOException) { System.out.println("Unknown file error occurred ..."); } finally { sInputFile.close(); } } // main } // class 3071 Java Question. Create an application named Numbers whose main() method holds two integer variables. Assign values to the variables. Pass both values to methods named sum() and difference(). Create the methods sum() and difference(); then compute the sum and difference between the values of two arguments, respectively. Each method should perform the appropriate computation and display the results. Save the application as Numbers.java. Please let me know what IDE was used and will run. 3072 Java Question. Create an application that calculates and displays the weekly salary for an employee who earns $25 an hour, works 40 regular hours, and 13 overtime hours, and earns time and one-half (wage * 1.5 for overtime hours worked). Create a separate method to do the calculation and return the result to the main() method to be displayed. Save the program as Salary.java. Please tell me what IDE that was used to create and will run. 3073 Java Show transcribed image text 7.27 (Identical arrays) The arrays list1 and list 2 are identical it they have the same contents. Write a method that returns true if list 1 and list 2 are identical, using the following header: public static boolean equals(int[] list1, int[] list2) Programming Exercises 283 Witte a test program that prompts the user to enter two lists of integers and displays whether the two are identical. Here are the sample runs. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list. 3074 Java Programming Questions. Follow the examples, please help me with the follwing methods. Show transcribed image text l)Methods with 1+ parameter. 0 returns (careful with parameter var types): Ex: A method that prints your first and last name (receive names as parameter) Public static void printName(String fName, String IName //receives 2 Strings for names // join names together seperated by a space and print name String fullName = (Name + ? Name; System.out.println(fullName); a. A method that adds two numbers together and prints the result (receive numbers) b. A method that turns inches and feet into lust inches (receives inches & feet) with 1+ parameter. 1 returns (careful with parameter var types: 2) Methods Ex: A method that received your first and last name and returns your full name (receive names) 3075 Java Programming questions. Follow the examples, could you please help me create methods with contracts? Show transcribed image text Create methods with contracts for the following: 1) Methods with 0 parameters, 0 returns: Ex: A method that prints hello a. A method that prints 3 lines of your address b. A method that uses input to get a string and prints the string c. A method that uses input to get two numbers and prints their total 2) Methods with 1 parameter. 0 returns (careful with parameter var types): Ex: A method that prints Mr. and your name (receive name as parameter a. A method that adds 10 to a number (receive number as parameter) b. A method that prints feet when given miles (receive miles as a parameter) 3076 Java Programming Show transcribed image text Week 7 Pair Exercise - Odds Calculator You volunteer your weekends at 305-Gambler, an anonymous helpline. After answering a few phone calls you start to realize that your callers have no idea what their probabilities for winning their games actually are. You decide on a strategy for counseling that introduces long-shot odds A????1n order to establish a baseline for comparison to the odds they actually have in their game of choice. Some of these longshot odds are: 3077 Java Programming Please Help!! I've already compiled 4 separate files into one to form "alice.txt" Everyone in my class needs help, so please help. As Alice is wandering about, she wonders: A????1How many letters of the English alphabet are in my story?A????1 Luckily, you were able to merge the individual files back together to the complete story in A????1Alice.txtA????1 and offer to help wondering Alice. Write a program that reads in the file A????1Alice.txtA????1 (in Blackboard) and counts the occurrences of regular letters in the English alphabet and prints their numbers out afterwards. Hints: - We are only interested in letters, not their case A????1 in turn, A????1aA????1 is the same as A????1AA????1 - String has a function .toLowerCase() - Read line by line - There are 26 letters in the alphabet 3078 Java Programming Assignment Task: Design a program that simulates rolling a 6-sided die and keeps track of which number comes up. Display your results after 6,000,000 rolls Variables, We need variables to keep track of how many times a number appears Instead of simulating rolling 1 6-sided die 6,000,000 times, simulate rolling 2 6-sided dice 1,000,000 times. The output should then show how many times the sum of the 2 dice appears. Thus, your output should show a count for 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 and 12. Note that no count for a roll of 1 is necessary because the minimum number for rolling two dice is 2. Programming requirements: You must use comments in your code to demonstrate how you can document your work. 3079 Java programing Create a program to enter grades and calculate averages and letter grades. 1. Need a class which will contain: a. Student Name b. Student Id c. Student Grades (an array of 3 grades) d. A constructor that clears the student data (use -1 for unset grades) e. Get functions for items a, b, and c, average, and letter grade f. Set functions for items a, n, and c g. Note that the get and set functions for Student grades need an argument for the grade index. 2. Need another class which will contain: a. An Array of Students (1 above) b. A count of number of students in use 3. You need to create a menu interface that allows you to: a. Add new students b. Enter test grades c. Display all the students with their names, ids, test grades, average, and letter grade d. Exit the program 4. Add comments and use proper indentation. 3080 java programing Create a program to enter grades and calculate averages and letter grades. 1. Need a class which will contain: a. Student Name b. Student Id c. Student Grades (an array of 3 grades) d. A constructor that clears the student data (use -1 for unset grades) e. Get functions for items a, b, and c, average, and letter grade f. Set functions for items a, n, and c g. Note that the get and set functions for Student grades need an argument for the grade index. 2. Need another class which will contain: a. An Array of Students (1 above) b. A count of number of students in use 3. You need to create a menu interface that allows you to: a. Add new students b. Enter test grades c. Display all the students with their names, ids, test grades, average, and letter grade d. Exit the program 4. Add comments and use proper indentation. Nice Features: A????1 I would like that system to accept a student with no grades, then later add one or more grades, and when all grades are entered, calculate the final average or grade. A????1 I would like the system to display the students in alphabetical order (no matter what order they are entered in) This project is a challenge. Do the best you can and I will grade it accordingly. Basically, I will award points for 1. Creating a Student class that can perform the tasks requested (30 points) 2. Creating an array of Student and loading it (20 points) 3. Modifying the data in that array (20 points) 4. Displaying results for all students (10 points) 5. Proper indentation, comments, and A????1Nice FeaturesA????1 items (20 points) 6. Note that submitting a program that does not compile is an automatic deduction of 20 points. If you have any questions, please contact me as soon as possible. An example menu might be: Enter A to Add Students Enter B to Enter Test Grades Enter C to Display Results Enter D to Exit Program Please select A, B, C, or D: For item B, you will need to prompt the user to enter the test number and then enter the value for each student for that test (if there is a previous value, you should display it and if the user enters the empty string, not change the value). 3081 JAVA Program question: Please show steps and explaination!! Thanks in advance! Write a JAVA program that counts the distinct permutations of several strings with repeated characters. Use the strings "AAAAAAA", "ABCDEFG", "AAABBBCCCC" and "AABBCCDDEE". Compare the counts of permutations to the multinomial coefficients. OUTPUT BELOW: Permutations of AAAAAAA, count: 1 multinomial: 1 Permutations of ABCDEFG, count: 5040 multinomial: 5040 Permutations of AAABBBCCCC, count: 4200 multinomial: 4200 Permutations of AABBCCDDEE, count: 113400 multinomial: 113400 3082 THIS IS A JAVA PROGRAM - PLEASE COMMENT THE CODE Write a program that tests your ESP (extrasensory perception). The program should randomly select the name of a color from the following list of words: Red, Green, Orange, Yellow To select a word, the program can generate a random number. For example, if the number is 0, the selected word is Red; if the number is 1, the selected word is Green; and so forth. Next, the program should ask the user to enter the color that the computer has selected. After the user has entered his or her guess, the program should display the name of the randomly selected color. The program should repeat this 10 times and then display the number of times the user correctly guessed the selected color. Be sure to modularize the program into methods that perform each major task. 3083 Java Program help Show transcribed image text Linear Regression : Linear regression draws a straight line through a group of data points such that the position and slope of the line minimizes the square of the vertical distance between the data points and the straight line. It fits the data in an intuitively satisfying and yet mathematically reproducible way. For linear regression to be valid, all data points should vary in exactly the same random way, and that variation should have a normal or ''Gaussian'' distribution - the familiar bell-shaped distribution. To illustrate the application of linear regression, this project Uses it to generate a trend line for the effect of nitrogen fertilizer on the yield of a crop of corn (maise). To guarantee that the required assumptions are met, we have created the data artificially, by adding a normally distributed random variable to a sloping straight line, with the same variance for all data points. Specifically, we added normal random number having a standard deviation of 25 to the straight line. Here's the equation: y = 50 + 100 * x + randomNumber The following plot shows one set of 10 data points, and the linear-regression fit to those data points The first sample session prints all of the data points used in the figure. The second sample session prints just the first 10 of 10,000 points used as the basis of the regression. Of course, your random number generator will not generate the same data values as those shown above, but the four values at the bottom of your output should be close to the four values we generated - which are close to the parameters used to generate the random data. Your job is to write the program that produces these results. To generate the first sample session above, initialize a two-dimensional array with the 10 sets of output values shown. To generate the second sample session above, import the java.util. Random package, use the zero-parameter constructor to instantiate a random-number generator, and have that generator call its nextGaussian method to generate a random variable with a Gaussian distribution whose mean value is zero and whose standard deviation is 1.0. (See Section 5.8 for more information.) 3084 java program help Show transcribed image text Linear Regression **: Linear regression draws a straight line through a group of data points such that the position and slope of the line minimizes the square of the vertical distance between the data points and the straight line. It fits the data in an intuitively satisfying and yet mathematically reproducible way. For linear regression to be valid, all data points should vary in exactly the same random way, and that variation should have a normal or ''Gaussian'' distribution - the familiar bell-shaped distribution. To illustrate the application of linear regression, this project uses it to generate a trend line for the effect of nitrogen fertilizer on the yield of a crop of corn (maise). To guarantee that the required assumptions are met, we have created the data artificially, by adding a normally distributed random variable to a sloping straight line, with the same variance for all data points. Specifically, we added normal random number having a standard deviation of 25 to the straight line. Here's the equation: y = 50 + 100 * x + randomNumber The following plot shows one set of 10 data points, and the linear-regression fit to those data points 3085 In Java, Program will convert English sentences to Morse Code. Ask user to enter a sentence in English to convert to Morse Code. Output the equivalent sentence in Morse Code. Use one blank between each Morse-coded letter & three blanks between each Morse-coded word. Sample output looks like : Morse Code reference chart: 3086 Java Program Build a Java Application using two classes that will sum the areas of any number and combination of triangles, rectangles, and circles. One class (CalcArea) will hold at least three methods; one method will calculate the area of a triangle, one method will calculate the area or a rectangle, and one will calculate the area of a circle. The other class (TotalArea) will allow a user to input any combination and number of the above shapes and determine the total area in square units. The TotalArea Class will not calculate the areas of any of the shapes; the CalcArea Methods must be called from the TotalArea Class and return the area values accordingly. Additional Requirements: - As part of your Design Step, include an UML Activity Diagram for the TotalArea Class - As part of your Design Step, include the UML Class Diagrams for both the CalcArea and Total Area Classes - As part of your TotalArea Class implementation, students must use at least one A????1whileA????1 or A????1forA????1 loop to gather dimension-input from the user - As part of your Test Plan, students will make sure to test different combinations of shapes and numbers of shapes - Outputs need to reflect the shape, dimensions, and area of each shape input along with the combined area 3087 JAVA PROBLEM Write the following methods and provide a program to test them: (a) double smallest(double x, double y, double z), returning the smallest of the arguments; (b) double average(double x, double y, double z), returning the average of the arguments. 3088 JAVA Please please help Show transcribed image text *6.2 (Sum the digit in an integer) Write a method that computes the sum of the digits in an integer. Use the following method header: public static int sumDigits(long n) For example. sumDigits(234) reurns 9(2 + 3 + 4). (Hint Use the % operator to extract digits. and the / operator to remove the extracted digit. For instance. to extract 4 from 234. use 234 X 10 (= 4). To remove 4 from 234. use 234 / 10 ( =23). Use a loop lo repeatedly extract and remove the digit until all the digits arc extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits. 3089 Java please help Show transcribed image text 7.8 (Average an array) Write two overloaded methods that return the average of an array with the following headers: public static int average(int array) public static double average(doublet] array) Write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value. 3090 Java please help Show transcribed image text (Statistics: compute deviation) Programming Exercise 5.45 computes the standard deviation of numbers. This exercise uses a different but equivalent formula to compute the standard deviation of n numbers. To compute the standard deviation with this formula, you have to store the individual numbers using an array, so that they can be used after the mean is obtained. Your program should contain the following methods: Write a test program that prompts the user to enter ten numbers and displays the mean and standard deviation as shown in the following sample run: 3091 Java please help Show transcribed image text 6.12 (Display Characters) Write a method that prints characters using the following header: public static void printChars(char ch1, char ch2, int numberPerline) This method prints the characters between ch1 and ch2 with the specified numbers per line. Write a test program that prints ten characters per line from 1 to Z. Characters are separated by exactly one space 3092 Java please help me Show transcribed image text Write a method to display a pattern as follows: 1 21 321 n n - 1 . . . 3 2 1 public static void displayPattern(int n) 3093 Java please help Show transcribed image text *6.19 (The MyTriangle class) Create a class named MyTriangle that contains the following two methods: /** Return true if the sum of any two sides is * greater than the third side. */ public static boolean isValid( double side1, double side2, double side3) /** Return tree area of the triangle. */ public static double area( double side1, double side2, double side3) Write a test program that reads three sides for a triangle and computes the area if the input is valid. Otherwise, it displays that the input is invalid. The formula for computing the area of a triangle is given in Programming Exercise 2.19. 3094 Java please help Show transcribed image text **6.30 (Game: craps) Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows: Roll two dice. Each die has six faces representing values 1, 2, ..., and 6, respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose: if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e., 4, 5, 6, 8,9, or 10), a point is established. Continue to roll the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win. Your program acts as a single player. Here are some sample runs. You rolled 5 + 6= 11 You win You rolled 1 + 2=3 You lose to. You rolled 4 + 4 = 8 point is 8 You rolled 6 + 2=8 You win You rolled 3 + 2=5 point is 5 You rolled 2 + 5=7 You lose 3095 Java please help Show transcribed image text S (Rmwial o?plkzion. pru a tax b1e) Listing 3.5 gives a program to coinpte x. Wrile a met&d fu cioinpuing x using the following trader p.?lic static ub1? cca?uteTaz(int status, &ub1e taab1eIncore) Chapter 6 Methods Use this method to itt a program that pr?ntii atax table for taxabk income from $50,000 to $60.000 with icrvaIs of $50 for all the following statuses: T.gabl. Marr4d J.Int Marr.d Hsid d kssme os QusUflng Seporate a Ne.. ________Wow.r) 30000 8688 6663 8688 7353 30030 8700 6673 8700 7363 $9930 11173 8138 11175 9840 60000 11188 8165 11188 9853 ffinr round the tax into icgers using Math,round (i.e., Math . round(coqiut.Tax(status. takabletncome)). 3096 Java please help Show transcribed image text *6.7 (Financial application: Compute the future investment value) Write a method that computes future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Programming Exercise 2.21. Use the following method header: public static double futurelnvestmentValue( double InvestnientAmount, double monthlylnterestRate, int years) For example, futurelnvestmentValue(10000, 0.05/12, 5) returns 12833.59. Write a test program that prompts the user to enter the investment amount (e.g., 1000) and the interest rate (e.g., 9%) and prints a (able that displays future value for the years from 1 to 30, as shown below; The amount invested: 1000 Annual interest rate: 9 Years Future Value 1 1093.80 , 2 1196.41 . . . 29 13467.25 30 14730.57 3097 Java please help Show transcribed image text 6.11 (Financial application: compute commissions) Write a method that computes the commission, using the scheme in Programming Exercise 5.39. The header of the method is as follows: public static double computeCommission(double salesAmount) Write a test program that displays the following table: 3098 Java please help Show transcribed image text (Palindrome integer) Write the methods with the following headers // Return the reversal of an integer, i .e., reverse(4S6) returns 654 public static int reverse (int number) // Return true if number is a palindrome public static boolean isPalindrome(int number) Use the reverse method to implement isPal indrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome. 3099 Java please help asap Show transcribed image text *6.7 (Financial appli cat ion: Compute the future investment value) Write a method that computes future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Programming Exercise 2.21. Use the following method header: public static double future lnvestmentvalue( double investment Amount, double monthlylnterest Rate, int years) For example, future lnvestmentValue(10000, 0.05/12, 5) returns 12833.59. Write a test program that prompts the user lo enter the investment amount (e.g., 1000) and the interest rate (e.g., 9%) and prints a table that displays future valuc for the years from 1 to 30, as shown below: 3100 JAVA Please help asap Show transcribed image text Listing 3.5 gives a program to compute tax. Write a method for computing tax using the following header: Use this method to write a program that prints a taxable income from 450,000 to $60,000 with intervals of 550 for all the following statuses: 3101 Java please help asap Show transcribed image text Exercise 1: Design and Implement a Java program (name it MinMaxAvg) that defines three methods as follows: Method max (int x, int y, int z) determines and returns the maximum value of three integer values. Method min (int X, Int y, int z) determine and returns the minimum value of three integer values, Method average (int x, int y, int z) determines and returns the average of three integer values Test the methods with different input value read from the user (in the main method). Design the man method of your program such that It allows the user to re-run the program with different Inputs (i. e.. use a loop structure). Document your code, and organize and space the Outputs property, Use escape characters to organize the outputs. Sample output is: 3102 Java please help asap Show transcribed image text Exercise 1: Design and implement a Java program (name it MinMaxAvg) that defines three methods as follows: Method max (int x, int y, Int z) determines and returns the maximum value of three integer values Method min (int X, int y, int z) determines and returns the minimum value of three integer values. Method average (int x, Int y, int z) determines and returns the average of three integer values Test the methods with different input value read from the user (in the main method) Design the main method of your program such that it allows the user to re-run the program with different inputs (i.e., use a loop structure). Document your code, and organize and space the outputs properly. Use escape characters to organize the outputs Sample output is You entered: 20 8 12 Max value: 20 Min value: 8 Average value: 13.33333333333 3103 Java Part 1: Item class Design, darw UML diagram, and implement a class called Item that represented an item that is being sold in a hardware shop. An item is defined by the following attributes: o itemNum: integer value that represented the item number o description: a string that contains a brief description of the item o price: a double value that gives the price of the item Include the following methods in your class: o Constructor o Getters and Setters o toString() o equlas() Part 2: InvoiceLine class: Design, darw UML diagram, and implement a class called InvoiceLine that a hardware store might use to represent a line that is added to an invoice. An InvoiceLine should include the following attributes: o itemSold: this is an object of Item class. o quantity: an integer that represents the number of units being purchased of this item. The class should include the following methods: o constructor that initializes the two attributes. o setters and getters methods. method named, o getLineTotal: that calculates and returns the total price for this line (i.e., quantity * item price). o toString() method that gives a one-line description of the invoice line. Part 3: Invoice Class: Design, darw UML diagram, and implement Invoice class is a class that represents an invoice that consists of 4 InvoiceLine at most. The class includes the following attributes: o invNumber: an integer to represent the invoice number o numItems: an integer that represents how many lines are there in the invoice. The number can be 0,1,2,3, or 4. o line1: an object of InvoiceLine class that represents an object added to the invoice o line2: : an object of InvoiceLine class that represents an object added to the invoice o line3:an object of InvoiceLine class that represents an object added to the invoice o line4:an object of InvoiceLine class that represents an object added to the invoice The class should contain the following methods: o Constructor: that creates an empty invoice and assigns a number to the invoice. o Getters and setters o addLine(): This method takes an InvoiceLine object as input and adds it to the invoice only if the invoice has less than 4 items. If the invoice has more than four item then this method should print an error message. o getInvoiceTotal: calculates and returns the total price for the invoice. o toString(): a price to print a nicely formatted invoice. Part 4: InvoiceDriver class Create a driver class to create an Invoice that includes 4 items and print the invoice. 3104 In java multithreaded client server socket programming Your multithreaded server will have an infinite loop to listen for connections. To shut down your server, you will have to interrupt it with a termination signal. Upon receiving the termination signal, your server must shut down gracefully, closing all sockets before exiting. You can design your program that best matches your programming styles. HTTP Client Your client should take the following command line arguments (in order): server name, port on which to contact the server, HTTP command (GET or PUT), and the path of the requested object on the server. In other words, assuming that your executable is named A????1myclientA????1, you should be able to run your program from the command line as follows: myclient hostname port command filename In response to a GET command, the client must: 1. connect to the server via a TCP connection 2. submit a valid HTTP/1.1 GET request to the server 3. read the serverA????1s response and display it In response to a PUT command, the client must: 1. Connect to the server via a TCP connection 2. submit a valid HTTP/1.1 PUT request to the server 3. send the file to the server 4. wait for the serverA????1s reply 5. read the serverA????1s response and display it HTTP Server Your server should take a command line argument that specifies the port number that the server will use to listen for incoming connection requests. In other words, assuming that your executable is named A????1myserverA????1, you should be able to run your server from the command line as follows: myserver port Your server must: 1. Create a socket with the specified port number 2. Listen for incoming connections from clients 3. When a client connection is accepted, read the HTTP request 4. Construct a valid HTTP response: a. When the server receives a GET request, it should either construct a A????1200 OKA????1 message followed by the requested object or a A????1404 Not FoundA????1 message. b. When the server receives a PUT request, it should save the file locally. c. If the received file is successfully saved, the server should construct a A????1200 OK File CreatedA????1 response. 5. Send the HTTP response over the TCP connection with the client 6. Close the client connection 7. Continue to A????1loopA????1 to listen for incoming connection 3105 java Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right) element as the pivot, rather than an arbitrary number. (This is similar to what happens in the quickSort1.java program in Listing 7.3.) Make sure your routine will work for arrays of three or fewer elements. To do so, you may need a few extra statements. 3106 In java language: Given a double from user, calc the square root and the quad root and print it. Limit the answers to 5 decimal places. import java.util.Scanner; class Challenge{ public static void main(String args[]){ Scanner scan = new Scanner(System.in); System.out.println("Enter a number:"); double x = scan.nextDouble(); ///{ Write your code here ///} } } 3107 JAVA Implement a radix sort as described in the last section of this chapter. It should handle variable amounts of data and variable numbers of digits in the key. You could make the number-base variable as well (so it can be something other than 10), but it will be hard to see whatA????1s happening unless you develop a routine to print values in different bases. 3108 JAVA Implement a radix sort as described in the last section of this chapter. It should handle variable amounts of data and variable numbers of digits in the key. You could make the number-base variable as well (so it can be something other than 10), but it will be hard to see whatA????1s happening unless you develop a routine to print values in different bases. 3109 JAVA HOMEWORK Tree of Integers! Objective: Trees sure are neat. LetAc€?cs take this slow and simple and make a tree of integers. Download this FILE, and the DRIVER and fill in the code to create a tree of integers. The class IntBSTree is given fill in the following methods insert: This method returns nothing and takes in an integer value that is then placed as a new node in the tree based on the binary tree properties. A reminder values greater than the parent go to the right subtree and values smaller go to the left subtree. Also it may be a good idea to use a recursive method in order to place these values. printInorder: This method which returns nothing and has no parameters prints the in order traversal of the tree. For in order traversal each left subtree must be visited, then the value is printed out, and finally each of the right subtrees is visited. It is a good idea to make a recursive method to assist with this. Also if done correctly in-order traversals print out each of the integers in ascending order. getDepth: The depth of a node is the number of edges from the root to that number. This method returns nothing and takes in a parameter corresponding to the integer value of a node whose depth is returned. If the value is not in the tree a -1 should be returned. Again a recursive helper method may be useful to solve this. Correct Print Out: Int BST Tester! Creating tree Populating Tree with values Testing insertion by in-order traversal 1 2 3 4 5 6 7 8 9 10 Getting depth of 6 4 Getting depth of 14 -1 Finally: Upload the .java file to the dropbox FILE: public class IntBSTree{ private class Node { private int data; private Node leftChild; private Node rightChild; public Node(int aData) { this.data = aData; this.leftChild = null; this.rightChild = null; } } private Node root; public IntBSTree() { root = null; } public void insert(int data) { //Code this } public void printInorder() { //Code this } public int getDepth(int value) { //Code this } } DRIVER FILE: import java.util.*; public class IntBSTreeTester { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Int BST Tester!"); System.out.println("Creating tree"); IntBSTree testTree = new IntBSTree(); System.out.println("Populating Tree with values"); int[] valArr = {4,8,10,2,1,7,3,5,9,6}; for(int i : valArr) { testTree.insert(i); } System.out.println("Testing insertion by in-order traversal"); testTree.printInorder(); System.out.println("Getting depth of 6"); System.out.println(testTree.getDepth(6)); System.out.println("Getting depth of 14"); System.out.println(testTree.getDepth(14)); } } EXAMPLE FOR THIS HW: public class LinkedBSTree> { private class Node { private T data; private Node leftChild; private Node rightChild; public Node(T aData) { this.data = aData; this.leftChild = null; this.rightChild = null; } } private Node root; public LinkedBSTree() { root = null; } public void insert(T data) { if(root == null) { root = new Node(data); } else insert(root,data); } public Node insert(Node aNode, T data) { if(aNode == null) { aNode = new Node(data); } else if(data.compareTo(aNode.data)<0)//Go left { aNode.leftChild = insert(aNode.leftChild,data); } else if(data.compareTo(aNode.data)>=0)//Go right { aNode.rightChild = insert(aNode.rightChild,data); } return aNode; } public boolean search(T data) { return recursiveSearch(root,data); } public boolean recursiveSearch(Node aNode, T data) { if(aNode == null) return false; if(aNode.data.compareTo(data)==0) return true; else if(aNode.data.compareTo(data)>0) return recursiveSearch(aNode.rightChild,data); else return recursiveSearch(aNode.leftChild,data); } public Node deleteMinFromTree(Node aNode) { if(aNode == null) return null; if(aNode.leftChild == null) return aNode; aNode.leftChild = deleteMinFromTree(aNode.leftChild); return aNode; } public Node findMinInTree(Node aNode) { if(aNode == null) return null; if(aNode.leftChild == null) return aNode; else return findMinInTree(aNode.leftChild); } public void delete(T value) { root = delete(root,value); } public Node delete(Node aNode, T value) { //Find the value if(aNode == null) return null; if(value.compareTo(aNode.data)<0) aNode.leftChild = delete(aNode.leftChild,value); else if(value.compareTo(aNode.data)>0) aNode.rightChild = delete(aNode.rightChild,value); else //Value is found { if(aNode.rightChild == null) return aNode.leftChild; if(aNode.leftChild == null) return aNode.rightChild; Node temp = aNode; aNode = findMinInTree(aNode.rightChild); aNode.rightChild = deleteMinFromTree(aNode.rightChild); aNode.leftChild = temp.leftChild; } return aNode; } public void printPreorder() { printPreorder(root); } public void printPreorder(Node aNode) { if(aNode == null) return; System.out.println(aNode.data.toString()); if(aNode.leftChild != null) printPreorder(aNode.leftChild); if(aNode.rightChild != null) printPreorder(aNode.rightChild); return; } public void printInorder() { printInorder(root); } public void printInorder(Node aNode) { if(aNode == null) return; if(aNode.leftChild != null) { printInorder(aNode.leftChild); } System.out.println(aNode.data.toString()); if(aNode.rightChild != null) { printInorder(aNode.rightChild); } return; } } import java.util.*; public class BSTreeTester { public static void main(String[] args) { // TODO Auto-generated method stub Random r = new Random(); final int MAX_VAL = 100; final int ARR_SIZE = 10; int[] valArray = new int[ARR_SIZE]; System.out.println("BS Tree tester!"); System.out.println("Populating an array of values"); for(int i=0;i { valArray[i] = r.nextInt(MAX_VAL); System.out.println(valArray[i]); } System.out.println("Creating a tree with values"); //LinkedBSTree lTree = new LinkedBSTree(); ArrayBSTree lTree = new ArrayBSTree(); for(int i=0;i { lTree.insert(valArray[i]); } System.out.println("Printing Preorder"); lTree.printPreorder(); System.out.println("Printing Inorder"); lTree.printInorder(); System.out.println("Removing the 5th element: "+valArray[4]); lTree.delete(valArray[4]); lTree.printInorder(); } } 3110 JAVA HOMEWORK Tree of Integers! Objective: Trees sure are neat. LetA????1s take this slow and simple and make a tree of integers. Download this FILE, and the DRIVER and fill in the code to create a tree of integers. The class IntBSTree is given fill in the following methods insert: This method returns nothing and takes in an integer value that is then placed as a new node in the tree based on the binary tree properties. A reminder values greater than the parent go to the right subtree and values smaller go to the left subtree. Also it may be a good idea to use a recursive method in order to place these values. printInorder: This method which returns nothing and has no parameters prints the in order traversal of the tree. For in order traversal each left subtree must be visited, then the value is printed out, and finally each of the right subtrees is visited. It is a good idea to make a recursive method to assist with this. Also if done correctly in-order traversals print out each of the integers in ascending order. getDepth: The depth of a node is the number of edges from the root to that number. This method returns nothing and takes in a parameter corresponding to the integer value of a node whose depth is returned. If the value is not in the tree a -1 should be returned. Again a recursive helper method may be useful to solve this. Correct Print Out: Int BST Tester! Creating tree Populating Tree with values Testing insertion by in-order traversal 1 2 3 4 5 6 7 8 9 10 Getting depth of 6 4 Getting depth of 14 -1 Finally: Upload the .java file to the dropbox FILE: public class IntBSTree{ private class Node { private int data; private Node leftChild; private Node rightChild; public Node(int aData) { this.data = aData; this.leftChild = null; this.rightChild = null; } } private Node root; public IntBSTree() { root = null; } public void insert(int data) { //Code this } public void printInorder() { //Code this } public int getDepth(int value) { //Code this } } DRIVER FILE: import java.util.*; public class IntBSTreeTester { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Int BST Tester!"); System.out.println("Creating tree"); IntBSTree testTree = new IntBSTree(); System.out.println("Populating Tree with values"); int[] valArr = {4,8,10,2,1,7,3,5,9,6}; for(int i : valArr) { testTree.insert(i); } System.out.println("Testing insertion by in-order traversal"); testTree.printInorder(); System.out.println("Getting depth of 6"); System.out.println(testTree.getDepth(6)); System.out.println("Getting depth of 14"); System.out.println(testTree.getDepth(14)); } } EXAMPLE FOR THIS HW: public class LinkedBSTree> { private class Node { private T data; private Node leftChild; private Node rightChild; public Node(T aData) { this.data = aData; this.leftChild = null; this.rightChild = null; } } private Node root; public LinkedBSTree() { root = null; } public void insert(T data) { if(root == null) { root = new Node(data); } else insert(root,data); } public Node insert(Node aNode, T data) { if(aNode == null) { aNode = new Node(data); } else if(data.compareTo(aNode.data)<0)//Go left { aNode.leftChild = insert(aNode.leftChild,data); } else if(data.compareTo(aNode.data)>=0)//Go right { aNode.rightChild = insert(aNode.rightChild,data); } return aNode; } public boolean search(T data) { return recursiveSearch(root,data); } public boolean recursiveSearch(Node aNode, T data) { if(aNode == null) return false; if(aNode.data.compareTo(data)==0) return true; else if(aNode.data.compareTo(data)>0) return recursiveSearch(aNode.rightChild,data); else return recursiveSearch(aNode.leftChild,data); } public Node deleteMinFromTree(Node aNode) { if(aNode == null) return null; if(aNode.leftChild == null) return aNode; aNode.leftChild = deleteMinFromTree(aNode.leftChild); return aNode; } public Node findMinInTree(Node aNode) { if(aNode == null) return null; if(aNode.leftChild == null) return aNode; else return findMinInTree(aNode.leftChild); } public void delete(T value) { root = delete(root,value); } public Node delete(Node aNode, T value) { //Find the value if(aNode == null) return null; if(value.compareTo(aNode.data)<0) aNode.leftChild = delete(aNode.leftChild,value); else if(value.compareTo(aNode.data)>0) aNode.rightChild = delete(aNode.rightChild,value); else //Value is found { if(aNode.rightChild == null) return aNode.leftChild; if(aNode.leftChild == null) return aNode.rightChild; Node temp = aNode; aNode = findMinInTree(aNode.rightChild); aNode.rightChild = deleteMinFromTree(aNode.rightChild); aNode.leftChild = temp.leftChild; } return aNode; } public void printPreorder() { printPreorder(root); } public void printPreorder(Node aNode) { if(aNode == null) return; System.out.println(aNode.data.toString()); if(aNode.leftChild != null) printPreorder(aNode.leftChild); if(aNode.rightChild != null) printPreorder(aNode.rightChild); return; } public void printInorder() { printInorder(root); } public void printInorder(Node aNode) { if(aNode == null) return; if(aNode.leftChild != null) { printInorder(aNode.leftChild); } System.out.println(aNode.data.toString()); if(aNode.rightChild != null) { printInorder(aNode.rightChild); } return; } } import java.util.*; public class BSTreeTester { public static void main(String[] args) { // TODO Auto-generated method stub Random r = new Random(); final int MAX_VAL = 100; final int ARR_SIZE = 10; int[] valArray = new int[ARR_SIZE]; System.out.println("BS Tree tester!"); System.out.println("Populating an array of values"); for(int i=0;i { valArray[i] = r.nextInt(MAX_VAL); System.out.println(valArray[i]); } System.out.println("Creating a tree with values"); //LinkedBSTree lTree = new LinkedBSTree(); ArrayBSTree lTree = new ArrayBSTree(); for(int i=0;i { lTree.insert(valArray[i]); } System.out.println("Printing Preorder"); lTree.printPreorder(); System.out.println("Printing Inorder"); lTree.printInorder(); System.out.println("Removing the 5th element: "+valArray[4]); lTree.delete(valArray[4]); lTree.printInorder(); } } 3111 Java help please Show transcribed image text *6.23 Occurrences of a specified character) Write a method hat finds the number of occurrences of a specified character in a string using the following header: public static int count(String str , shar a) 240 Chapter 6 Methods For example, count ( welcome , e) returns 2. Write a test program that prompts the user to enter a string followed by a character and display the number of occurrences of the character in the string. 3112 in java and give in c++ Show transcribed image text 7. The method getValueFromFile is public and returns an int. It accepts no arguments. The method is capable of throwing an IOException and a FileNotFoundException. Write the header for this method. in java and give in c++ 3113 Java: How do I display a large number of numbers and tick marks on a JSlider? The below squished the display of numbers and tick marks. public Window() { setTitle("Test Window Title"); setSize(1000, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 800, 500); slider.setMajorTickSpacing(100); slider.setMinorTickSpacing(25); slider.setPaintTicks(true); slider.setPaintLabels(true); JPanel panel = new JPanel(); panel.add(slider); add(panel); setVisible(true); } 3114 ava is different to most programming languages that implement an A????1exceptionA????1 concept, by having two kinds that are distinguished (only) at compile-time: checked and unchecked exceptions. Read Unchecked ExceptionsA????1The Controversy, and discuss your interests and concerns as a programmer in this separation. 3115 In Java Design a linear-time certification algorithm to check whether an array pq is a min-oriented heap using public static boolean isMinOrientedHeap(int[] a) which returns true if input array is a minheap and false if it doesn't not. Thank you! 3116 This is java. You are creating a BigInt class. It can hold one number that is very large. The first part of the assignment is to create a constructor that can take a String and convert it to your internal representation of a BigInt. Use an array or ArrayList to hold the integer. Below is a Demo program that your BigInt class should be able to handle. Keep in mind that the number could be negative. Also keep in mind you will need to add and subtract Multiply Devide and modulus BigInt values. Below the Demo are several lines of code dealing with methods of the String class. You must be able to work with String methods to both take the string from the constructor and turn it into the integers in the ArrayList and then turn the ArrayList of integers to a string in the toString() method. The toString() method is called automatically when a BigInt instance is put in a System.out.println() as demonstrated by the next line of code. System.out.println("new BigInt value is " B1); Here the string "new BigInt value is " is concatenated with the BigInt B1. The System class knows to invoke the BigInt toString()method. The following code will do the same thing: System.out.println("new BigInt value is " B1.toString()); Below the string methods is the Bottle class. Study it carefully. The Bottle class encapsulates a Bottle. The private instance variable pennies holds the contents of the bottle. It is a bottle of pennies. There are methods of the Bottle class that do operations on Bottle values. Study each method. The add method: public Bottle add(Bottle J). it should run the following demo. import java.util.Scanner; public class BigInt_Add_Sub_Mul_Div_Mod_Demo { public static void main(String[] args) { BigInt b1; BigInt b2; BigInt b3; b1 = new BigInt("-0"); b2 = new BigInt("+0"); b3 = b1.add(b2); System.out.println("1) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b1 = new BigInt("1"); b2 = new BigInt("1"); b3 = b1.add(b2); System.out.println("\n2) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-1"); b2 = new BigInt("1"); b3 = b1.add(b2); System.out.println("\n3) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("1"); b2 = new BigInt("-1"); b3 = b1.add(b2); System.out.println("\n4) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); b3 = b1.modulus(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-1"); b2 = new BigInt("-1"); b3 = b1.add(b2); System.out.println("\n5) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("+1"); b2 = new BigInt("+1"); b3 = b1.add(b2); System.out.println("\n6) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-100"); b3 = b1.add(b2); b2 = new BigInt("100"); System.out.println("\n7) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("100"); b2 = new BigInt("-100"); b3 = b1.add(b2); System.out.println("\n8) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-100"); b2 = new BigInt("-100"); b3 = b1.add(b2); System.out.println("\n9) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("100"); b2 = new BigInt("100"); b3 = b1.add(b2); System.out.println("\n10) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("200"); b2 = new BigInt("-0"); b3 = b1.add(b2); System.out.println("\n11) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); //b3 = b1.divideBy(b2); //System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); //b3 = b1.modulus(b2); //System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-200"); b2 = new BigInt("-0"); b3 = b1.add(b2); System.out.println("\n12) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); //b3 = b1.divideBy(b2); //System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); //b3 = b1.modulus(b2); //System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-0"); b2 = new BigInt("200"); b3 = b1.add(b2); System.out.println("\n13) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-0"); b2 = new BigInt("-200"); b3 = b1.add(b2); System.out.println("\n14) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("37"); b2 = new BigInt("26"); b3 = b1.add(b2); System.out.println("\n15) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-200111111111111111199999999"); b2 = new BigInt("3333333333333388888888888888888888555555555555555555555555"); b3 = b1.add(b2); System.out.println("\n19) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("66666666666666666666677777777777777777777711111111111111111200"); b2 = new BigInt("-3333333333333333333344444444444"); b3 = b1.add(b2); System.out.println("\n20) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("-66666666666666666666677777777777777777777711111111111111111200"); b2 = new BigInt("-333333"); b3 = b1.add(b2); System.out.println("\n21) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); b1 = new BigInt("6666666"); b2 = new BigInt("3333333333333333333344444444444444444444455555555555555550"); b3 = b1.add(b2); System.out.println("\n22) sum b3 is " + b1 +" + " + b2 + " = " + b3); b3 = b1.subtract(b2); System.out.println("difference b3 is " + b1 +" - " + b2 + " = " + b3); b3 = b1.multiply(b2); System.out.println("product b3 is " + b1 +" * " + b2 + " = " + b3); b3 = b1.divideBy(b2); System.out.println("quotient b3 is " + b1 +" / " + b2 + " = " + b3); b3 = b1.modulus(b2); System.out.println("modulus b3 is " + b1 +" mod " + b2 + " = " + b3); } } 3117 In JAVA, we are to create a class A uml diagram that helps with the Java coding process: Show transcribed image text Write your own version of a generic class named MyQueue that will create a static queue of any data type. Submit only the class itself, do not include a driver program. I will import your class into my own driver program and test it myself as part of grading. Be sure to include the following methods: ??Constructor ? accepts an integer argument specifying the length of the queue. ??enqueue ? Accepts a value to put in the queue. Throws an exception if the queue is full. ?-.dequeue ? Returns a value from the queue. Throws an exception if the queue is empty. ??isFull ? Returns true if the queue is full, false otherwise. ??isEmpty - Returns true if the queue is empty, false otherwise. ??toString ? Returns a string representation of the queue. You may not use the Java API queue container(java.util.Queue). For the exception, Just throw an Exception, i.e., new Exception(Something) 3118 Java Consider this method declaration: public static void quiz3 (int i){ if (i>1) { quiz3(i/2); } System.out.println("*"); } How many asterisks are printed by the method call quiz3? 3119 in JAVA CODE? Computing the LCS using Linear Memory We can use a clever trick to actually compute the LCS without storing the entire table by using a divide and conquer approach. Rather than compute the LCS by backtracking over the entire table, we can actually break up the table into very small chunks and compute the LCS recursively. Throughout this process, we never have to store more than two rows of the table. A????1 First, we start by computing rows from top to bottom. Each row is computed left to right as we did in the previous algorithms for computing edit distance. Again, we can use only two rows, so that the entire table does not need to be stored. However, instead of computing all the rows, we stop at the middle row, i.e. row ? m 2 ? where m is the length of the string aligned along the left. This row is called the forward middle row because it is computed in the forward direction. A????1 Second, we compute the other rows from bottom to top. Each of these rows is computed right to left (reverse direction). Note that the cells three neighbors are now inverted. Before a new cell can be computed, its right neighbor, bottom neighbor, and diagonal bottom-right neighbor must be computed. Again, instead of computing all the rows, we stop at the bottom middle row, i.e. row ? m 2 ? + 1. This row is called the reverse middle row. Figure 4 shows the computation of the two middle rows. Note how the bottom rows are computed in the reverse direction and note that the rightmost column and bottom row are initialized in reverse order. After computing the middle rows, the next step is to scan the middle rows cell by cell and figure out exactly where the LCS would have backtracked. We can do this by adding the cell value in the forward middle row to the value in the diagonal bottom-right cell of the reverse middle row. We scan from left to right and remember the last location of the minimum edit distance. Figure 5 shows how to use the middle rows to compute the edit distance. Note that it is important to scan the middle rows cell by cell from left to right and record the LAST location of the minimum edit distance. Otherwise your algorithm will not produce a correct LCS. This location actually tells us where the backtracking will occur. We can use this location to split the table into four quarters and we can discard two of the quarters To compute the LCS we only need to examine the two quarter tables shown above. Note that the table is always horizontally split in the middle (? m 2 ?), but the vertical split depends on where the minimum edit distance appears. This allows us to determine where the LCS will backtrack. After we have split the table into two quarter tables, we can apply the same algorithm to the two quarter tables and break them into even smaller quarters. We can recursively apply this process until all the sub-tables are broken into tables which have either one row or one column. Figure 7 illustrates how the table might be recursively split into sub-tables with either one row or one column. Finally, to compute the LCS we need to report if the symbol in the one remaining column matches any of the symbols in the remaining rows, or if the symbol in the one remaining row matches any of the symbols in the remaining columns. This is the base case of the recursive algorithm. The purpose of the divide and conquer recursive algorithm is to break the table into these base cases. This complicated approach has a very simple recursive algorithm that ensures that the LCS is computed in the proper order. void lcs_recursive(const Sequence & X, const Sequence & Y, Sequence & LCS) { if (X.size() == 1) { Compare X[0] to each symbol in Y[0, ..., Y.size()-1] If there is a symbol match push_back X[0] on to LCS } else if (Y.size() == 1) { Compare Y[0] to each symbol in X[0, ..., X.size()-1] If there is a symbol match push_back Y[0] on to LCS } else { Compute the middle rows as described above. Find the horizontal (x) and vertical (y) split indices for the table. Generate Sequence X_front = X[0, ..., x] Generate Sequence Y_front = Y[0, ..., y] Generate Sequence X_back = X[x+1, ..., X.size()-1] Generate Sequence Y_back = Y[y+1, ..., Y.size()-1] lcs_recursive(X_front, Y_front, LCS); lcs_recursive(X_back, Y_back, LCS); } } A????1 The horizontal split index (x) corresponds to the index of string X where the table is split horizontally. In the example shown in Figure 6 the horizontal split index would be three (NOT four, four would be the row index). This corresponds to symbol t. This should always be equal to X.size()/2 - 1. The minus one is necessary because our arrays start with index zero. A????1 The vertical split index (y) corresponds to the index of string Y where the table is split vertically. In the example shown in Figure 6 the horizontal split index would be three (NOT four, four would be the column index). This corresponds to symbol a . Implement the LCS algorithm that uses linear memory. This function computes and returns the longest common subsequence of two sequences. This function should be implemented using the recursive linear memory algorithm 3120 Java Assignment //Remote Grade book Service Write a client that will send a grade book entry to a server. The user should also be able to add courses. And be able to view all entries for the selected grade book. The entries can simply be printed as strings. The client also needs to be able to switch the grade book it is working with. Working with the server. The client works with a grade book (adding and viewing entries) by selecting a grade book listed by the server. First it must request the list from the server. Then respond with an index corresponding to the list sent by the server. The server will then use that grade book for adding and viewing entries. Server Commands GetStudents: - returns a : separated list of names for currently selected course. hw: and exam: - registers a grade book entry. ListEntries: - returns one string for each entry, ends by sending EOL: AddCourse: - expects a course name after the colon. CourseList: - returns : separated list of course names SelectCourse: - expects an index number after the colon that corresponds to the CourseList. Assignment ground work The server side is provided along with some skeleton code for the client. The skeleton methods in the client are suggestions. Feel free to modify them and you will probably want to add more. Separate Entries in the code below ExamEntry.java Person.java GradeBook.java GradeBookEntry.java GradeBookEntryClient.java GradeBookEntryServer.java GradeConverter.java HomeworkEntry.java START OF THE CODE EXAMENTRY.JAVA Starts Here import java.util.Scanner; public class ExamEntry extends GradeBookEntry { private int curve; private int numericGrade; public ExamEntry( String examName ){ super(examName); } public ExamEntry( String examName, int curve ){ super(examName); this.curve = curve; } public int getCurve() { return curve; } public void setCurve(int curve) { this.curve = curve; } public void setNumericGrade(int numericGrade) { this.numericGrade = numericGrade; } @Override public int getNumericGrade() { return numericGrade + curve; } @Override public void getData(){ Scanner reader = new Scanner(System.in); System.out.println("Enter the numeric grade: "); boolean success = false; while (!success) { try { this.numericGrade = reader.nextInt(); } catch (Exception e) { System.out.println("Invalid, please try again:"); } if( numericGrade >= 0 && numericGrade <= 100 ){ success = true; }else { System.out.println("Must be 0-100, Please try again:"); } } reader.nextLine(); System.out.println("Enter the curve: "); success = false; while (!success) { try { this.curve = reader.nextInt(); } catch (NumberFormatException e) { System.out.println("Invalid, please try again:"); } if( curve >= 0 && curve <= 100 ){ success = true; }else { System.out.println("Must be 0-100, Please try again:"); } } } @Override public String toString(){ return this.getAssessmentName() + "\n" + this.getStudent().getName() + "\n" + this.getNumericGrade() + "\n" + this.getCurve(); } } PERSON.JAVA Starts Here import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Person { private String name; private int age; private String email; private String ssn; public Person(){ name = null; age = 0; email = null; ssn = null; } public Person(String name){ // Keyword this distinguishes between the member of this class, // and the parameter name; this.name = name; // the rest of the member variables will have default values } // This constructor initializes everything public Person( String name, int age, String email, String ssn){ this.name = name; this.age = age; this.email = email; this.ssn = ssn; } // This is a copy constructor. It takes an object of the same // class, and copies all the member variables over. // Then you will have two separate objects with identical data public Person( Person person){ this.name = person.name; this.age = person.age; this.email = person.email; this.ssn = person.ssn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public boolean isEmailValid(String email){ return email.matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$"); } public void setEmail(String email) { this.email = email; } public void getData(){ Scanner reader = new Scanner(System.in); System.out.print("Enter the person's name: "); name = reader.nextLine(); System.out.print("Enter the person's age: "); age = reader.nextInt(); reader.nextLine(); System.out.print("Enter the person's email: "); email = reader.nextLine(); if( !isEmailValid(email)){ System.out.println("Hey that's not a valid address!"); } System.out.println("Enter SSN: "); ssn = reader.nextLine(); } /** * New method for Lab. Uses a scanner to read the file data. * It is assumed that only data for one person is in the file. * @param fileName The name of the file with person data. */ public void getDataFromFile(String fileName){ Scanner reader = null; try { reader = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { System.out.println("Error opening file"); } if (null != reader) { name = reader.nextLine(); age = reader.nextInt(); reader.nextLine(); email = reader.nextLine(); ssn = reader.nextLine(); } } /** * New method for lab. This method writes the person data to a file. * @param fileName Name of the file write the data. */ public void saveToFile(String fileName){ BufferedWriter writer = null; try { // This will overwrite any previous file with this name writer = new BufferedWriter(new FileWriter(new File(fileName))); } catch (IOException e) { System.out.println("Undable to open file for writing!"); } try { // The write method simply takes a string and writes it to the file. writer.write(name + "\n"); writer.write(age + "\n"); writer.write(email + "\n"); writer.write(ssn + "\n"); writer.close(); } catch (IOException e) { System.out.println("Error writing to file!"); } } public String getId(){ return ssn; } public String toString(){ return "Name: " + name + "\nAge: " + age + "\nemail: " + email + "\nssn: " + ssn; } public static void main( String args[] ){ Person person = new Person("John Smith", 34, "[email protected]", "111-22-3333"); person.saveToFile("johnSmith.txt"); Person john = new Person(); john.getDataFromFile("johnSmith.txt"); System.out.println("Read from file:\n" + john.toString()); } } GRADEBOOK.JAVA Starts Here import java.util.ArrayList; import java.util.Scanner; public class GradeBook { private String course; private ArrayList students = new ArrayList(); private ArrayList entries = new ArrayList(); public GradeBook(String course){ this.course = course; } public String getCourse() { return course; } public ArrayList getStudents() { return students; } public ArrayList getEntries() { return entries; } public void setCourse(String course) { this.course = course; } public void addStudent( Person student ){ students.add(student); } public void addEntry(){ System.out.println("Grade which student: "); for (int i = 0; i < students.size(); i++) { System.out.println(i + " " + students.get(i).getName()); } Scanner reader = new Scanner(System.in); int studentIndex = reader.nextInt(); reader.nextLine(); System.out.println("Enter the assessment name: "); String assessmentName = reader.nextLine(); System.out.println("Homework (1) or exam (2): "); int entryType = reader.nextInt(); reader.nextLine(); GradeBookEntry newEntry; if( entryType == 1 ){ newEntry = new HomeworkEntry(assessmentName); }else{ newEntry = new ExamEntry(assessmentName); } newEntry.getData(); newEntry.setStudent(students.get(studentIndex)); entries.add(newEntry); } public static GradeBookEntry createEntry(String studentName){ Scanner reader = new Scanner(System.in); System.out.println("Enter the assessment name: "); String assessmentName = reader.nextLine(); System.out.println("Homework (1) or exam (2): "); int entryType = reader.nextInt(); reader.nextLine(); GradeBookEntry newEntry; if( entryType == 1 ){ newEntry = new HomeworkEntry(assessmentName); }else{ newEntry = new ExamEntry(assessmentName); } newEntry.getData(); newEntry.setStudent(new Person(studentName)); return newEntry; } public void putEntry( GradeBookEntry entry ){ entries.add(entry); } public void listGrades(){ for( int i=0; i= 90 ){ return "A"; } else if( numberGrade >= 80 ) { return "B"; } else if( numberGrade >= 70 ){ return "C"; } else if( numberGrade >= 60 ){ return "D"; } else{ return "F"; } } /** * This method gets input from the user * @return a grade in number format from 0-100 */ public int getNumberGrade(){ // declare and intialize variables int userInput=0; Scanner reader = new Scanner(System.in); // get the user input System.out.print("Enter the number grade: "); userInput = reader.nextInt(); // return the input to the caller of this method return userInput; } /** * @param args */ public static void main(String[] args) { GradeConverter converter = new GradeConverter(); int input = converter.getNumberGrade(); String letterGrade = converter.convertGrade(input); System.out.println("The letter grade for " + input + " is " + letterGrade); } } HOMEWORKENTRY.JAVA Starts Here import java.util.Scanner; public class HomeworkEntry extends GradeBookEntry { private int numericGrade; public HomeworkEntry( String assignmentName){ super(assignmentName); } @Override public int getNumericGrade() { return numericGrade; } public void setNumericGrade(int numericGrade) { this.numericGrade = numericGrade; } @Override public void getData(){ Scanner reader = new Scanner(System.in); System.out.println("Enter the numeric grade: "); boolean success = false; while (!success) { try { this.numericGrade = reader.nextInt(); } catch (Exception e) { System.out.println("Invalid, please try again:"); } if( numericGrade >= 0 && numericGrade <= 100 ){ success = true; }else { System.out.println("Must be 0-100, Please try again:"); } } reader.nextLine(); } @Override public String toString(){ return this.getAssessmentName() + "\n" + this.getStudent().getName() + "\n" + this.getNumericGrade(); } } 3121 Java application HW JavaDoc.zip The Javadoc for the application has been generated for you. Unzip the file into a directory and then open the file index.html to view the documentation. https://www.dropbox.com/s/udy1p5otn2dvg6v/javadoc%202.zip?dl=0 Link to HW https://elearning.uh.edu/bbcswebdav/pid-1821798-dt-content-rid-12231499_1/courses/H_20151_CIS_2348_18061_MAIN/CIS%202348%20Homework %203%20S2015.pdf Basic Application In this homework, you will create the basic application that reads input from a datafile and writes the results to the console. In the next homework, you will enhance the application by adding database functionality. Program Flow The following pseudocode shows the required flow of the program. Begin for each line in inventory file do determine inventory type based on type, create object to hold data (FoodItem or Household Item) populate item with appropriate data (weight, etc) store in inventory list end for each item in inventory list do print item end for each household item in inventory do determine shipping cost print shipping cost end End Program Output For the supplied input file, the output should be as shown below (dates will be different!) Item banana -- Shelf Life: 5 -- Remove from Shelf: Thu Mar 12 22:07:56 CDT 2015 -- Calories: 200.00 Item bread -- Shelf Life: 10 -- Remove from Shelf: Tue Mar 17 22:07:56 CDT 2015 -- Calories: 120.00 Item toaster -- Weight: 5 Item washer -- Weight: 200 Item toaster shipped. Shipping cost is $100.00 Item washer shipped. Shipping cost is $4,000.00 Business Rules There are two types of items tracked in the system: food items and household (durable) items. A????1 Food Items Food items are edible (we hope!) and perishable. An edible item has calories, while a perishable item has a limited shelf life. The item must be removed from the shelf when it expires. The expiration date is simply expiration date = date placed in inventory + shelf life in days A????1 Household Items Household items have unlimited shelf life, so they do not have an expiration date. They do have (sometimes substantial) weight. Their weight is taken into account when determining the shipping cost. The shipping cost is also higher when the item is shipped on the weekend. UML Diagram The classes and interfaces required for the application have been defined for you, and are shown in the diagram below. Dotted lines indicate interfaces while solid lines indicate inheritance. Your application must implement all classes and interfaces as shown. JavaDoc.zip The Javadoc for the application has been generated for you. Unzip the file into a directory and then open the file index.html to view the documentation. https://www.dropbox.com/s/udy1p5otn2dvg6v/javadoc%202.zip?dl=0 Link to HW https://elearning.uh.edu/bbcswebdav/pid-1821798-dt-content-rid-12231499_1/courses/H_20151_CIS_2348_18061_MAIN/CIS%202348%20Homework %203%20S2015.pdf 3122 Java algorithms to be included in your analysis are: Selection Sort, Insertion Sort, Merge Sort, Quick Sort. You will run and time the algorithms under the following inputs: List of 100 numbers drawn from 0--9. List of 100 numbers drawn from 0--99. List of 100 numbers drawn from 0--999. List of 1000 numbers drawn from 0--99. List of 1000 numbers drawn from 0--999. List of 1000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--999. List of 10000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--9999. List of 100000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--999999. code so far: import java.util.Random; public class SortingAlgorithms { /** * @param args */ public static void main(String[] args) { int[] list = new int[10000000]; Random rand = new Random(); for (int i = 0; i < list.length; ++i) { list[i] = rand.nextInt(1000000); } long initTime = System.currentTimeMillis(); quickSort(list); long finalTime = System.currentTimeMillis(); System.out.println(finalTime - initTime); // System.out.println(Arrays.toString(quickSort(new int[] { 621, 306, 173, 937, // 345, 42, 450 }))); } public static int[] countingSort(int[] numbers) { int[] counter = new int[1000000]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[numbers[i]]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = 0; i < result.length; ++i) { result[--counter[numbers[i]]] = numbers[i]; } return result; } public static int[] radixSort(int[] numbers, int radix) { int[] result = numbers; for (int pos = 1; pos <= radix; ++pos) { result = modCountingSort(result, pos); } return result; } private static int getDigit(int number, int pos) { int pow = (int)Math.pow(10, pos); int rem = number % pow; return rem / (pow / 10); } public static int[] modCountingSort(int[] numbers, int pos) { int[] counter = new int[10]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[getDigit(numbers[i], pos)]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = result.length-1; i> = 0; --i) { result[--counter[getDigit(numbers[i], pos)]] = numbers[i]; } return result; } public static int[] quickSort(int[] numbers) { quickSortHelper(numbers, 0, numbers.length - 1); return numbers; } private static void quickSortHelper(int[] numbers, int init, int last) { if ((last - init) < 1 || (last < 0)) { return; } int pivotIndex = partitionList(numbers, init, last); quickSortHelper(numbers, init, pivotIndex - 1); quickSortHelper(numbers, pivotIndex + 1, last); } private static int partitionList(int[] numbers, int init, int last) { int lastAssignedPos = init; for (int i = init; i < last; ++i) { if (numbers[i]< numbers[last]) { swap(numbers, lastAssignedPos, i); ++lastAssignedPos; } } swap(numbers, last, lastAssignedPos); return lastAssignedPos; } public static int[] mergeSort(int[] numbers) { return mergeSortHelper(numbers, 0, numbers.length - 1); } private static int[] mergeSortHelper(int[] numbers, int init, int last) { if ((last - init) == 0) { return new int[] { numbers[last] }; } int mid = (last + init) / 2; int[] subList1 = mergeSortHelper(numbers, init, mid); int[] subList2 = mergeSortHelper(numbers, mid + 1, last); return merge(subList1, subList2); } private static int[] merge(int[] subList1, int[] subList2) { int[] result = new int[subList1.length + subList2.length]; int sub1First = 0; int sub2First = 0; for (int i = 0; i < result.length; ++i) { if (sub1First == subList1.length) { result[i] = subList2[sub2First++]; } else if (sub2First == subList2.length) { result[i] = subList1[sub1First++]; } else if (subList1[sub1First] <= subList2[sub2First]) { result[i] = subList1[sub1First++]; } else { result[i] = subList2[sub2First++]; } } return result; } public static int[] bubbleSort(int[] numbers) { boolean swapped = false; do { swapped = false; for (int i = 0; i < (numbers.length - 1); ++i) { if (numbers[i] > numbers[i + 1]) { swap(numbers, i, i + 1); swapped = true; } } } while (swapped); return numbers; } public static int[] selectionSort(int[] numbers) { for (int i = 0; i < numbers.length - 1; ++i) { int minIndex = i; for (int j = i + 1; j < numbers.length; ++j) { if (numbers[j] < numbers[minIndex]) minIndex = j; } swap(numbers, minIndex, i); } return numbers; } public static int[] insertionSort(int[] numbers) { for (int i = 1; i < numbers.length; ++i) { for (int j = i; j > 0; --j) { if (numbers[j] < numbers[j - 1]) { swap(numbers, j, j - 1); } else { break; } } } return numbers; } private static void swap(int[] numbers, int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } public static int[] recInsertSort(int[] list) { return recSortHelper(0, list); } private static int[] insert(int init, int[] list) { for (int i = init; i < list.length - 1; ++i) { if (list[i] > list[i + 1]) { swap(list, i, i + 1); } else { break; } } return list; } private static int[] recSortHelper(int init, int[] list) { if (init == (list.length - 1)) { return list; } else { return insert(init, recSortHelper(init + 1, list)); } } } 3123 Java algorithms to be included in your analysis are: Selection Sort, Insertion Sort, Merge Sort, Quick Sort. You will run and time the algorithms under the following inputs: List of 100 numbers drawn from 0--9. List of 100 numbers drawn from 0--99. List of 100 numbers drawn from 0--999. List of 1000 numbers drawn from 0--99. List of 1000 numbers drawn from 0--999. List of 1000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--999. List of 10000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--9999. List of 100000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--999999. code so far: import java.util.Random; public class SortingAlgorithms { /** * @param args */ public static void main(String[] args) { int[] list = new int[10000000]; Random rand = new Random(); for (int i = 0; i < list.length; ++i) { list[i] = rand.nextInt(1000000); } long initTime = System.currentTimeMillis(); quickSort(list); long finalTime = System.currentTimeMillis(); System.out.println(finalTime - initTime); // System.out.println(Arrays.toString(quickSort(new int[] { 621, 306, 173, 937, // 345, 42, 450 }))); } public static int[] countingSort(int[] numbers) { int[] counter = new int[1000000]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[numbers[i]]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = 0; i < result.length; ++i) { result[--counter[numbers[i]]] = numbers[i]; } return result; } public static int[] radixSort(int[] numbers, int radix) { int[] result = numbers; for (int pos = 1; pos <= radix; ++pos) { result = modCountingSort(result, pos); } return result; } private static int getDigit(int number, int pos) { int pow = (int)Math.pow(10, pos); int rem = number % pow; return rem / (pow / 10); } public static int[] modCountingSort(int[] numbers, int pos) { int[] counter = new int[10]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[getDigit(numbers[i], pos)]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = result.length-1; i >= 0; --i) { result[--counter[getDigit(numbers[i], pos)]] = numbers[i]; } return result; } public static int[] quickSort(int[] numbers) { quickSortHelper(numbers, 0, numbers.length - 1); return numbers; } private static void quickSortHelper(int[] numbers, int init, int last) { if ((last - init) < 1 || (last < 0)) { return; } int pivotIndex = partitionList(numbers, init, last); quickSortHelper(numbers, init, pivotIndex - 1); quickSortHelper(numbers, pivotIndex + 1, last); } private static int partitionList(int[] numbers, int init, int last) { int lastAssignedPos = init; for (int i = init; i < last; ++i) { if (numbers[i] < numbers[last]) { swap(numbers, lastAssignedPos, i); ++lastAssignedPos; } } swap(numbers, last, lastAssignedPos); return lastAssignedPos; } public static int[] mergeSort(int[] numbers) { return mergeSortHelper(numbers, 0, numbers.length - 1); } private static int[] mergeSortHelper(int[] numbers, int init, int last) { if ((last - init) == 0) { return new int[] { numbers[last] }; } int mid = (last + init) / 2; int[] subList1 = mergeSortHelper(numbers, init, mid); int[] subList2 = mergeSortHelper(numbers, mid + 1, last); return merge(subList1, subList2); } private static int[] merge(int[] subList1, int[] subList2) { int[] result = new int[subList1.length + subList2.length]; int sub1First = 0; int sub2First = 0; for (int i = 0; i < result.length; ++i) { if (sub1First == subList1.length) { result[i] = subList2[sub2First++]; } else if (sub2First == subList2.length) { result[i] = subList1[sub1First++]; } else if (subList1[sub1First] <= subList2[sub2First]) { result[i] = subList1[sub1First++]; } else { result[i] = subList2[sub2First++]; } } return result; } public static int[] bubbleSort(int[] numbers) { boolean swapped = false; do { swapped = false; for (int i = 0; i < (numbers.length - 1); ++i) { if (numbers[i] > numbers[i + 1]) { swap(numbers, i, i + 1); swapped = true; } } } while (swapped); return numbers; } public static int[] selectionSort(int[] numbers) { for (int i = 0; i < numbers.length - 1; ++i) { int minIndex = i; for (int j = i + 1; j < numbers.length; ++j) { if (numbers[j] < numbers[minIndex]) minIndex = j; } swap(numbers, minIndex, i); } return numbers; } public static int[] insertionSort(int[] numbers) { for (int i = 1; i < numbers.length; ++i) { for (int j = i; j > 0; --j) { if (numbers[j] < numbers[j - 1]) { swap(numbers, j, j - 1); } else { break; } } } return numbers; } private static void swap(int[] numbers, int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } public static int[] recInsertSort(int[] list) { return recSortHelper(0, list); } private static int[] insert(int init, int[] list) { for (int i = init; i < list.length - 1; ++i) { if (list[i] > list[i + 1]) { swap(list, i, i + 1); } else { break; } } return list; } private static int[] recSortHelper(int init, int[] list) { if (init == (list.length - 1)) { return list; } else { return insert(init, recSortHelper(init + 1, list)); } } } 3124 Java algorithms to be included in your analysis are: Selection Sort, Insertion Sort, Merge Sort, Quick Sort. You will run and time the algorithms under the following inputs: List of 100 numbers drawn from 0--9. List of 100 numbers drawn from 0--99. List of 100 numbers drawn from 0--999. List of 1000 numbers drawn from 0--99. List of 1000 numbers drawn from 0--999. List of 1000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--999. List of 10000 numbers drawn from 0--9999. List of 10000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--9999. List of 100000 numbers drawn from 0--99999. List of 100000 numbers drawn from 0--999999. code so far: import java.util.Random; public class SortingAlgorithms { /** * @param args */ public static void main(String[] args) { int[] list = new int[10000000]; Random rand = new Random(); for (int i = 0; i < list.length; ++i) { list[i] = rand.nextInt(1000000); } long initTime = System.currentTimeMillis(); quickSort(list); long finalTime = System.currentTimeMillis(); System.out.println(finalTime - initTime); // System.out.println(Arrays.toString(quickSort(new int[] { 621, 306, 173, 937, // 345, 42, 450 }))); } public static int[] countingSort(int[] numbers) { int[] counter = new int[1000000]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[numbers[i]]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = 0; i < result.length; ++i) { result[--counter[numbers[i]]] = numbers[i]; } return result; } public static int[] radixSort(int[] numbers, int radix) { int[] result = numbers; for (int pos = 1; pos <= radix; ++pos) { result = modCountingSort(result, pos); } return result; } private static int getDigit(int number, int pos) { int pow = (int)Math.pow(10, pos); int rem = number % pow; return rem / (pow / 10); } public static int[] modCountingSort(int[] numbers, int pos) { int[] counter = new int[10]; int[] result = new int[numbers.length]; for (int i = 0; i < numbers.length; ++i) { ++counter[getDigit(numbers[i], pos)]; } for (int i = 1; i < counter.length; ++i) { counter[i] += counter[i - 1]; } for (int i = result.length-1; i >= 0; --i) { result[--counter[getDigit(numbers[i], pos)]] = numbers[i]; } return result; } public static int[] quickSort(int[] numbers) { quickSortHelper(numbers, 0, numbers.length - 1); return numbers; } private static void quickSortHelper(int[] numbers, int init, int last) { if ((last - init) < 1 || (last < 0)) { return; } int pivotIndex = partitionList(numbers, init, last); quickSortHelper(numbers, init, pivotIndex - 1); quickSortHelper(numbers, pivotIndex + 1, last); } private static int partitionList(int[] numbers, int init, int last) { int lastAssignedPos = init; for (int i = init; i < last; ++i) { if (numbers[i] < numbers[last]) { swap(numbers, lastAssignedPos, i); ++lastAssignedPos; } } swap(numbers, last, lastAssignedPos); return lastAssignedPos; } public static int[] mergeSort(int[] numbers) { return mergeSortHelper(numbers, 0, numbers.length - 1); } private static int[] mergeSortHelper(int[] numbers, int init, int last) { if ((last - init) == 0) { return new int[] { numbers[last] }; } int mid = (last + init) / 2; int[] subList1 = mergeSortHelper(numbers, init, mid); int[] subList2 = mergeSortHelper(numbers, mid + 1, last); return merge(subList1, subList2); } private static int[] merge(int[] subList1, int[] subList2) { int[] result = new int[subList1.length + subList2.length]; int sub1First = 0; int sub2First = 0; for (int i = 0; i < result.length; ++i) { if (sub1First == subList1.length) { result[i] = subList2[sub2First++]; } else if (sub2First == subList2.length) { result[i] = subList1[sub1First++]; } else if (subList1[sub1First] <= subList2[sub2First]) { result[i] = subList1[sub1First++]; } else { result[i] = subList2[sub2First++]; } } return result; } public static int[] bubbleSort(int[] numbers) { boolean swapped = false; do { swapped = false; for (int i = 0; i < (numbers.length - 1); ++i) { if (numbers[i] > numbers[i + 1]) { swap(numbers, i, i + 1); swapped = true; } } } while (swapped); return numbers; } public static int[] selectionSort(int[] numbers) { for (int i = 0; i < numbers.length - 1; ++i) { int minIndex = i; for (int j = i + 1; j < numbers.length; ++j) { if (numbers[j] < numbers[minIndex]) minIndex = j; } swap(numbers, minIndex, i); } return numbers; } public static int[] insertionSort(int[] numbers) { for (int i = 1; i < numbers.length; ++i) { for (int j = i; j > 0; --j) { if (numbers[j] < numbers[j - 1]) { swap(numbers, j, j - 1); } else { break; } } } return numbers; } private static void swap(int[] numbers, int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } public static int[] recInsertSort(int[] list) { return recSortHelper(0, list); } private static int[] insert(int init, int[] list) { for (int i = init; i < list.length - 1; ++i) { if (list[i] > list[i + 1]) { swap(list, i, i + 1); } else { break; } } return list; } private static int[] recSortHelper(int init, int[] list) { if (init == (list.length - 1)) { return list; } else { return insert(init, recSortHelper(init + 1, list)); } } } 3125 When you have to iterate a reader where the number of items to read is unknown, and the only way to do is it to keep reading until you hit the end. This is often the place you need an endless loop. There is the always true that indicates there must be a break or return statement somewhere inside the block. int offset = 0; while(true) { Record r = Read(offset); if(r == null) { break; } // do work offset++; } There is the double read for loop method. Record r = Read(0); for(int offset = 0; r != null; offset++) { r = Read(offset); if(r != null) { // do work } } There is the single read while loop. Not all languages support this method. int offset = 0; Record r = null; while((r = Read(++offset)) != null) { // do work } I'm wondering which approach is the least likely to introduce a bug, most readable and commonly used. Every time I have to write one of these I think "there has to be a better way". 3126 I am having issues writing a Method to called Stutter that replaces every value with two of that value as a static method with a single argument that is not changed. My code simple outputs no values. Please assist. import java.util.*; // Class ArrayIntList can be used to store a list of integers. public class ArrayIntList implements Iterable { private int[] elementData; // list of integers private int size = 0; // current number of elements in the list public static final int DEFAULT_CAPACITY = 10; // post: constructs an empty list of default capacity public ArrayIntList() { this(DEFAULT_CAPACITY); } // pre : capacity >= 0 // post: constructs an empty list with the given capacity private ArrayIntList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be at least 0: " + capacity); } elementData = new int[capacity]; } // for creating test cases more easily public ArrayIntList(int... elements) { this(Math.max(DEFAULT_CAPACITY, elements.length * 2)); for (int n : elements) { add(n); } } // for creating test cases more easily (a dupe of the above constructor) public static ArrayIntList withValues(int... elements) { ArrayIntList list = new ArrayIntList(Math.max(DEFAULT_CAPACITY, elements.length * 2)); for (int n : elements) { list.add(n); } return list; } // for creating test cases more easily public ArrayIntList(int element, boolean notCapacity) { this(); add(element); } // for creating test cases more easily public ArrayIntList(Collection elements) { this(Math.max(DEFAULT_CAPACITY, elements.size() * 2)); for (int n : elements) { add(n); } } // copy constructor; for creating test cases more easily public ArrayIntList(ArrayIntList list) { this(Math.max(DEFAULT_CAPACITY, list.size() * 2)); addAll(list); } // pre : size() < capacity (elementData.length) // post: appends the given value to the end of the list public void add(int value) { add(size, value); } // pre: size() < capacity (elementData.length) && 0 <= index <= size() // post: inserts the given value at the given index, shifting subsequent // values right public void add(int index, int value) { checkIndex(index, 0, size); ensureCapacity(size + 1); for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; } // post: appends all values in the given list to the end of this list public void addAll(ArrayIntList other) { for (int i = 0; i < other.size; i++) { add(other.elementData[i]); } } // post: list is empty public void clear() { size = 0; } // post: returns true if the given value is contained in the list, false otherwise public boolean contains(int value) { return indexOf(value) != -1; } // post: ensures that the underlying array has the given capacity; if not, // the size is doubled (or more if given capacity is even larger) public void ensureCapacity(int capacity) { if (capacity > elementData.length) { int newCapacity = elementData.length * 2 + 1; if (capacity > newCapacity) { newCapacity = capacity; } int[] newList = new int[newCapacity]; for (int i = 0; i < size; i++) { newList[i] = elementData[i]; } elementData = newList; } } // returns true if o is an ArrayIntList with the same size and elements as this one public boolean equals(Object o) { if (!(o instanceof ArrayIntList)) { return false; } ArrayIntList other = (ArrayIntList) o; if (this.size != other.size) { return false; } for (int i = 0; i < size; i++) { if (elementData[i] != other.elementData[i]) { return false; } } return true; } // pre : 0 <= index < size() // post: returns the integer at the given index in the list public int get(int index) { checkIndex(index); return elementData[index]; } // post: returns capacity of this list's underlying array public int getCapacity() { return elementData.length; } // post : returns the position of the first occurence of the given // value (-1 if not found) public int indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1; } // post: returns true if list is empty, false otherwise public boolean isEmpty() { return size == 0; } // post: returns an iterator for this list public Iterator iterator() { return new ArrayIntListIterator(this); } // pre : 0 <= index < size() // post: removes value at the given index, shifting subsequent values left public void remove(int index) { checkIndex(index); for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; } // post: removes all occurrences of the values in the given list from this list public void removeAll(ArrayIntList other) { int newSize = 0; for (int i = 0; i < size; i++) { if (!other.contains(elementData[i])) { elementData[newSize] = elementData[i]; newSize++; } size = newSize; } } // pre : 0 <= index < size() // post: replaces the integer at the given index with the given value public void set(int index, int value) { checkIndex(index); elementData[index] = value; } // post: returns the current number of elements in the list public int size() { return size; } // post: returns an array version of the contents of this list public int[] toArray() { return Arrays.copyOf(elementData, size); } // post: creates a comma-separated, bracketed version of the list public String toString() { String result = "["; for (int i = 0; i < size; i++) { if (i > 0) { result += ", "; } if (i < elementData.length) { result += elementData[i]; } else { // student's code is bogus; OOB result += "OOB!"; } } result += "]"; return result; } // helpers to make sure indexes do not fall out of bounds private void checkIndex(int index) { checkIndex(index, 0, size - 1); } private void checkIndex(int index, int min, int max) { if (!(min <= index && index <= max)) { throw new ArrayIndexOutOfBoundsException("Illegal index " + index + "; must be between " + min + " and " + max + "\n" + "list : " + toString() + " (size=" + size + ")\n" + "array: " + Arrays.toString(elementData) + " (capacity=" + elementData.length + ")"); } } // Stuart Reges // 4/4/05 // // The ArrayIntListIterator class provides a set of utilities for iterating // over an ArrayIntList and possibly removing values from the list. private static class ArrayIntListIterator implements Iterator { private ArrayIntList list; // list to iterate over private int position; // current position within the list private boolean removeOK; // whether it's okay to remove now // pre : list != null // post: constructs an iterator for the given list public ArrayIntListIterator(ArrayIntList list) { this.list = list; position = 0; removeOK = false; } // post: returns true if there are more elements left, false otherwise public boolean hasNext() { return position < list.size(); } // pre : hasNext() // post: returns the next element in the iteration public Integer next() { if (!hasNext()) throw new NoSuchElementException(); int result = list.get(position); position++; removeOK = true; return result; } // pre : next() has been called without a call on remove (i.e., at most one // call per call on next) // post: removes the last element returned by the iterator public void remove() { if (!removeOK) throw new IllegalStateException(); list.remove(position - 1); position--; removeOK = false; } } public static ArrayIntList stutter(ArrayIntList list) { int i = 0; ArrayIntList newList = new ArrayIntList(); while (i < list.size()-1) { newList.helperAdd(i, list.get(i), list.size()-1, list); i += 2; } return newList; } public void helperAdd(int index, int value, int size, ArrayIntList helper) { checkIndex(index, 0, size); ensureCapacity(size + 1); for (int i = size; i > index; i--) { helper.set(i, helper.get(i-1)); } helper.set(index, value); size++; 3127 I am having issues inputting a dividebyzero command in c++. It is for a basic calculator. What do I need to do to declare it and what is proper basic code? 3128 I am having an issue with my python code were if the user has more than one expense entry it does not display the correct over and under budget output. It works just fine with only one expense but not if there is multiples. Here is my code currently: # this program will take the users monthly budget and subtract their monthly # expenses to see if they are over or under budget. # Get the budget keep_going = 'y' budget = float(input("Enter your budget for this month: $")) whilekeep_going == 'y': # Initialize accumulator total = 0.0 # Get expenses expenses = float(input("Enter your expenses: $")) total = total + expenses keep_going = input("Do you have more expenses? ") if total > budget: print("You went over budget") else: print("You are under budget") 3129 I am having an issue with my python code below. If the user has more than one expense for the month it does not display the correct over or under budget output. If there is only one expense it works just fine. # this program will take the users monthly budget and subtract their monthly # expenses to see if they are over or under budget. # Get the budget keep_going = 'y' budget = float(input("Enter your budget for this month: $")) whilekeep_going == 'y': # Initialize accumulator total = 0.0 # Get expenses expenses = float(input("Enter your expenses: $")) total = total + expenses keep_going = input("Do you have more expenses? ") if total > budget: print("You went over budget") else: print("You are under budget") 3130 Isolate last octet in IP address I need to list the last octet of an IP address in one column of excel. If A1 has the IP address, I would like A2 to show the last octet of the IP address in A1. I tried this, but when the last octet was only 2 digits, it gave me .xx instead of just xx. It would probably do similar when the last octet is 1 digit. =RIGHT(A1,FIND("~",SUBSTITUTE(A1,".","~",1))) Thanks your for help !! 3131 1. If iron is an object, the statement Console.Write(iron); automatically invokes the ________ method Ans. 1. By abstracting out the attributes (data) and the behaviors(processes on the data), you can create a(n) __________to serve as template from which many objects of that type can be instantiated. Ans. 3132 about ipv4 header:- a) The IPv4 header has two length fields. Which are they and what are the purposes and limitations of each? (2p) b) What is the purpose of the TTL (time-to-live) field? How do routers handle the TTL field when forwarding a datagram? (2p) c) Is the IPv4 header checksum end-to-end or hop-by-hop? Why? (2p) d)Why usually is the IP header presented as rows of 4 bytes and why is the header length always given in multiple of 32 bytes? (2p) e) Which fields of the IP header change from router to router? (2p) 3133 about ipv4 header:- f) The IP header checksum only verifies the integrity of IP header. Discuss the pros and cons of doing the checksum on the header part versus on the entire packet? (2p) g) Why is there a shortage of IP version 4 addresses although the total address space contains many unused addresses? (2p) h) Explain the operation and implementation of the A????1tracerouteA????1 command in Unix? [2] i) Distinguish between the concepts of sub-netting and supernetting (CIDR) and why are both needed? [2] 3134 I have been involved in a number of MVC.NET and c# desktop projects in our company over the last year or so while also managing to kept my nose poked into other projects (in a read-only learning capacity of course). From this I've noticed that across the various projects and teams there is a-lot of functionality that has been well designed against good interfaces and abstractions. Because we tend to like our own work at times, I noticed a couple of projects had the exact same class, method copied into it as it had obviously worked on one and so was easily moved to a new project (probably by the same developer who originally wrote it) I mentioned this fact in one of our programmer meetings we have occasionally and suggested we pull some of this functionality into a core company library that we can build up over time and use across multiple projects. Everyone agreed and I started looking into this possibility. However, I've come across a stumbling block pretty early on. Our team primarily focuses on MVC at the moment and we have projects mainly in 2.0 but are starting to branch to 3.0. We also have a number of desktop applications that might benefit from some shared classes and basic helper methods. Initially when creating this DLL I included some shared classes that could be used across any project type (Web, Client etc) but then I started looking at adding some shared modules that would be useful in our MVC applications only. However this meant I had to include a reference to some Microsoft Web DLL's in order to leverage some of the classes I was creating (at this stage MVC 2.0). Now my issue is that we have a shared DLL that has references to web specific libraries that could also possibly be used in a client application. Not only that, our DLL referenced initially MVC 2.0 and we will eventually move onto MVC 3.0 for all projects. But alot of the classes in this library I expect to still be relevant to MVC 3 etc Our code within this DLL is separated into it's own namespaces such as: CompanyDLL.Primitives CompanyDLL.Web.Mvc CompanyDLL.Helpers etc etc So, my questions are: Is it OK to do a shared library like this, or if we have web specific features in it should we create a separate web DLL only targeted at a specific framework or MVC version? If it's OK, what kind of issues might we face when using the library that references MVC 2 in a MVC 3 project for example. I would be thinking that we might run into some sort of compatibility issue, or even issues where the developers using the library doesn't realize they need MVC 2.0 libraries. They might only want to use some of the generic classes etc The concept seemed like a good idea at the time, but I'm starting to think maybe it's not really a practical solution. But the number of times I've seen copied classes and methods across projects because they are proven tested code is a bit unnerving to be perfectly honest! UPDATED: Further to Bernards answer which I have taken on board and seems good advice. However I want to create some shared classes that will probably be useful in both MVC 2 and MVC 3 projects. However my shared assembly will have to reference one of the MVC frameworks in order for me to create my shared classes in the first place. So further to expand on my Q2 above. If I wanted a MVC 3 web solution would I have to have a shared CompanyDLL.Web.Mvc3 project that would then specifically be referencing MVC 3? Would that mean copying over all the code from my CompanyDLL.Web.Mvc2 solution to this new Mvc3 shared project? It seems I'm missing some fundamental designing skills in the creation of shared assemblies and building and referencing against different framework versions. Or it might just be as simple as we suck it up and create a CompanyDLL.Web.Mvc2, CompanyDLL.Web.Mvc3, CompanyDLL.Web.Mvc4 etc etc libraries... 3135 Inventory Management You have a business buying and selling Widgets. There are many ways to keep track of your Widget inventory, but two common ways are LIFO and FIFO. The profit computed using the two methods will be very different. LIFO uses the cost of the Widgets bought last to compute profit. FIFO uses the cost of the Widgets bought first to compute the profit. Thus, since the cost of an item increases over time in an inflationary economy, LIFO reports lower profit than FIFO. LIFO is often used to report income for tax purposes, while FIFO is used to report profit to shareholders. 1. Create an array-based deque implementation (ArrayDeque). Your implementation should not use shifting. Instead, allow the items to move around the interior of the array. To do this, you will need to store both the index of the front and the back. Allow array resizing if the array runs out of room. The (public) operations required by the Deque ADT are listed in a Deque interface (Deque.h). 2. Create a deque-based stack (DequeStack) and a deque-based queue (DequeuQueue) using your ArrayDeque implementation. DequeStack has to extend abstract class Stack and have just one private field of type Deque. DequeQueue should be implemented analogically. 3. Implement the following methods of a WidgetManager: void buyWidgets(double cost, int numToBuy) double sellWidgets(double cost, int numToSell) 4. Test your implementation in the way you like. You may write a driver that will allow you to buy and sell Widgets and will report the profit (loss) when you sell Widgets. You may adapt Prof. Boshart's driver that can be downloaded from here: mboshart.dyndns.org/boshart/2110programs/prog2/InventoryDriver.cpp You may write google tests instead of the driver. Your tests won't be graded but your implementations of the above mentioned classes. Submit to the dropbox your implementation of the classes: - ArrayDeque (file ArrayDeque.h) - DequeStack (file DequeStack.h) - DequeQueue (file DequeStack.h) and functions buyWidets and sellWidgets (file WidgetManager.cpp) 4 files in total You don't have to provide any documentation for this project. Starting project can be found in the repository (InventoryManager) and additionally will be sent together (ZIPped) with this document. Interaction1 Sample interaction with the user. In this case user first chose LIFO management style and then he bought: 5 widgets, each worth $6 3 widgets, each worth $2 7 widgets, each worth $9 Next, he sold 8 widgets $20 each. In this way he gained $95, since he sold the last 7 widgets he bought, each of which was worth $9 (so he gained 7x($20-$9) = $77 on these widgets) and also 1 widget that he payed $2 for (so he gained 1x($20-$2)=$18). On this transaction he gained $95 (=$77+$18). 3136 Intro to java I'm working on this project in eclipse, and I haven't started yet. Any help is appreciated. http://cs.boisestate.edu/~cs121/projects/p3/writeup.html 3137 This is for an Intro. to C++ course, therefore it should be made within the capabilities of such student. In other words, please consider answering the way a newbie would. Thank You. Show transcribed image text If there IS input failure, clears the failure, clears the input buffer (look at Ch 3), re-prompts for a double, and attempts again to get console input into a temporary double. The function cannot exit without returning a console entered double. You must use a loop to achieve this. Part 2 - Main Write a main program that asks the user for input into two doubles and an operator. Use the getDouble function to get the doubles. After this call Calc to get the result of the operation. Example: OUTPUT Enter a number: 12 Enter an operator: ? Enter a number: 3 12+3 is 15 Allow the user the option to continue entering more values (repeat the above operation) or quit. Remember, you must handle bad data entered for the numeric entries. Example: Enter a number: John !! Invalid Input!! Enter a number: Commodore 64 !! Invalid Input!! Enter a number: 12 Enter an operator: - Enter a number: 4 12-4 is 8 Part 1 ? Function definitions Calc Write a function called Calc that accepts two doubles and a char. This function will return either the sum, difference, product, or division of the two floats based on the following table: Char value operator + addition - subtraction * or x multiplication / division For example: Given: float x = 5; float y = 3; char operator = Calc(x. operator. y) -> would return x * y or 15.0 Given: operator = ?-? ; CaIc(x,operator,y) - > would return 5 - 3 or 2.0 Remember to check for division by zero. Trap on this condition. Print out DIV BY ZERO! to the screen and return zero rather than performing the division. getDouble Write a function that accepts nothing and: Prompts the user for input of a number Gets console input into a temporary double ? If there is NO input failure returns the double value 3138 I am interested to know how many real world web application servers are hosted by windows? I am going to learn C# and ASP.NET and want to convert my self from an embedded developer to a web app developer. My friends told me that there are ways more Linux based servers than windows servers. He also mentioned the Java skills stack is much more useful than .NET in the world of web application. My experience of Java and C# are rougly the same. I am an experienced C++ developer though. Can anyone give me some suggestion about it? Many thanks 3139 The intent of this assignment is to expose you to writing a program that makes use of repetition (looping) control in the C++ programming language. Toward this end, you will write a program that inputs and only accepts temperature below a specific threshold and wind speeds above a specific threshold. The program will use the input data to calculate a series of Wind Chill Indexes (WCI). BACKGROUND The higher the wind speed, the quicker a body cools. To quantify this wind speed chilling effect, both the U.S. and Canadian weather services have determined wind chill temperatures. In the U.S., a wind chill (or A????1feels like temperatureA????1) can be calculated for temperatures below 50A????1F and wind speed above 4 mph. In Canada, the same technique is used for temperatures below 10A????1C and wind speeds above 4.8 km/hr. An approximation of the official wind chill temperature can be derived using the following formula: WCI = K1 + 0.6125Ta A????1 K2Ws0.16 + K3TaWs0.16 Symbol Meaning Metric Units (Canada) U.S. Customary Units WCI Wind Chill Index A????1C A????1F Ta Measured temperature A????1C A????1F Ws Wind speed km/hr mi/hr K1 Conversion factor 13.12 35.74 K2 Conversion factor 11.37 35.75 K3 Conversion factor 0.3965 0.4275 REQUIREMENTS Write and implement a command-line C++ program that meets the following requirements: 1.Name the program file WindChill.cpp . Create the main() function within this file. 2.Prompt the user for temperature, wind speed and unit of measure for the temperature. You can assume the speed unit will match based upon country. 3.Validate all inputs by asking the user to re-enter invalid data. Only accept, A????1FA????1, A????1fA????1, A????1CA????1, or A????1cA????1 for the unit measure on temperature. Do not accept temperature above the appropriate threshold or wind speed below the appropriate threshold. 4.Using standard fixed-point notation, display at most two numbers to the right of the decimal. 5.Output two (2) formatted tables of temperatures, wind speeds and the associated Wind Chill index. For Table 1: Produce a list of temperatures that range from 2 degrees above the user specified temperature down through 2 degrees below the user specified temperature in 1 degree increments, including the user specified wind speed and the resulting WCI. Your table should provide results in the matching units of measure based upon what temperature that the user entered. Also, your tables should not provide data for any temperature above the threshold or wind speed that is below the threshold. Here is an example output had the user provided 35A????1F with a wind speed of 9 mph. Temperature 37F Wind Speed 9 mph WCI 30.07F 36F 9 mph 28.85F 35F 9 mph 27.63F 34F 9 mph 26.41F 33F 9 mph 25.19F For Table 2: Produce a list of wind speeds from 4 units of speed below the user specified temperature up through 4 units of speed above the user specified wind speed in 2 units of measure increments. Here is the sample output for Table 2 for the above example: Wind Speed Temperature 5 mph 35F WCI 30.28F 7 mph 35F 28.79F 9 mph 35F 27.63F 11 mph 35F 26.67F 13 mph 35F 25.84F 5.Alternative Bonus Challenge: In addition to submitting your project early, you can create a slightly more A????1helpfulA????1 program. Rather than producing 2 tables as shown above, you can create 1 combined table that combines information from both tables. However, this single table needs to not only combine all information from both tables but additional information where a WCI is computed for each wind speed at each of the temperatures within the ranges. Below is an example how this advanced table could look: Temperature 37F 36F 35F 34F 33F 3140 Wind Speed WCI 5mph 32.62F 7mph 31.19F 9mph 30.07F 11mph 29.15F 13mph 28.36F 5mph 31.45F 7mph 29.99F 9mph 28.85F 11mph 27.91F 13mph 27.10F 5mph 30.28F 7mph 28.80F 9mph 27.63F 11mph 26.67F 13mph 25.94F 5mph 29.12F 7mph 27.60F 9mph 26.41F 11mph 25.43F 13mph 24.59F 5mph 27.95F 7mph 26.40F 9mph 25.19F 11mph 24.19F 13mph 23.33F The intent of this assignment is to expose you to writing a program that makes use of repetition (looping) control in the C++ programming language. Toward this end, you will write a program that inputs and only accepts temperature below a specific threshold and wind speeds above a specific threshold. The program will use the input data to calculate a series of Wind Chill Indexes (WCI). BACKGROUND The higher the wind speed, the quicker a body cools. To quantify this wind speed chilling effect, both the U.S. and Canadian weather services have determined wind chill temperatures. In the U.S., a wind chill (or A????1feels like temperatureA????1) can be calculated for temperatures below 50A????1F and wind speed above 4 mph. In Canada, the same technique is used for temperatures below 10A????1C and wind speeds above 4.8 km/hr. An approximation of the official wind chill temperature can be derived using the following formula: WCI = K1 + 0.6125Ta A????1 K2Ws0.16 + K3TaWs0.16 Symbol Meaning Metric Units (Canada) U.S. Customary Units WCI Wind Chill Index A????1C A????1F Ta Measured temperature A????1C A????1F Ws Wind speed km/hr mi/hr K1 Conversion factor 13.12 35.74 K2 Conversion factor 11.37 35.75 K3 Conversion factor 0.3965 0.4275 REQUIREMENTS Write and implement a command-line C++ program that meets the following requirements: 1.Name the program file WindChill.cpp . Create the main() function within this file. 2.Prompt the user for temperature, wind speed and unit of measure for the temperature. You can assume the speed unit will match based upon country. 3.Validate all inputs by asking the user to re-enter invalid data. Only accept, A????1FA????1, A????1fA????1, A????1CA????1, or A????1cA????1 for the unit measure on temperature. Do not accept temperature above the appropriate threshold or wind speed below the appropriate threshold. 4.Using standard fixed-point notation, display at most two numbers to the right of the decimal. 5.Output two (2) formatted tables of temperatures, wind speeds and the associated Wind Chill index. For Table 1: Produce a list of temperatures that range from 2 degrees above the user specified temperature down through 2 degrees below the user specified temperature in 1 degree increments, including the user specified wind speed and the resulting WCI. Your table should provide results in the matching units of measure based upon what temperature that the user entered. Also, your tables should not provide data for any temperature above the threshold or wind speed that is below the threshold. Here is an example output had the user provided 35A????1F with a wind speed of 9 mph. Temperature Wind Speed WCI 37F 9 mph 30.07F 36F 9 mph 28.85F 35F 9 mph 27.63F 34F 9 mph 26.41F 33F 9 mph 25.19F For Table 2: Produce a list of wind speeds from 4 units of speed below the user specified temperature up through 4 units of speed above the user specified wind speed in 2 units of measure increments. Here is the sample output for Table 2 for the above example: Wind Speed Temperature 5 mph 35F WCI 30.28F 7 mph 35F 28.79F 9 mph 35F 27.63F 11 mph 35F 26.67F 13 mph 35F 25.84F 5.Alternative Bonus Challenge: In addition to submitting your project early, you can create a slightly more A????1helpfulA????1 program. Rather than producing 2 tables as shown above, you can create 1 combined table that combines information from both tables. However, this single table needs to not only combine all information from both tables but additional information where a WCI is computed for each wind speed at each of the temperatures within the ranges. Below is an example how this advanced table could look: Temperature 37F 36F 35F 34F Wind Speed WCI 5mph 32.62F 7mph 31.19F 9mph 30.07F 11mph 29.15F 13mph 28.36F 5mph 31.45F 7mph 29.99F 9mph 28.85F 11mph 27.91F 13mph 27.10F 5mph 30.28F 7mph 28.80F 9mph 27.63F 11mph 26.67F 13mph 25.94F 5mph 29.12F 7mph 27.60F 9mph 26.41F 11mph 25.43F 13mph 24.59F 33F 3141 5mph 27.95F 7mph 26.40F 9mph 25.19F 11mph 24.19F 13mph 23.33F Intel 32 bit assembly flags Show transcribed image text 1. Pill in the contents of the registers/flags after the execution of the corresponding instructions: (29 points) 3142 int mostLandings(vector &v,int startInt,int endInt) { int i = 0; int numDice = 2; int sidesOnDice = 6; int Index = 0; int score = 0; int MostLandings = 0; do { score = score + rollNdice(numDice, sidesOnDice) + startInt; if (score <= endInt ) { v.at(i) = score - 1; } ++i; } while(v.at(i) <= endInt); if (Index == v.at(0)) { ++MostLandings; } Index = v.at(0); return Index; Above is a part of my code to find the most landings on a board game. Here is a description of what I am to find. rollNDice simulates rolling N dice, each of which has the specified number of sides parameters: two integers by value: first integer: the number of dice to roll, by value second integer - the number of sides on the dice, by value return type: integer, the summation of all N dice rolls mostLandings returns the cell on the board with the most "landings", within an inclusive interval parameters: a vector; two integers first parameter: the game board vector, by const reference second parameter: the start of the interval to be tested, by value third parameter: the end of the interval to be tested, by value return type: integer, the index of the first cell in the interval with the most landings I have the first function completed. But now for the second one. I have no idea what to do. When I run the function I get the error, terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check And have no idea how to fix that. here is the code to my main function cout << "How many sides of the board are there? "; cin >> n; cout << endl << "How many spots are there on each side? "; cin >> k; cout << endl << "How many simulations? "; cin >> numSimulations; endInt = n * k; cout << endl << "The following spots on each side have the most landings:"; for (i = 0; i>> http://ge.tt/5njSjKC2/v/0 I will give 2000 points by providing another link if satisfied with the work :) >>>>>>>>>>>>>>Instruction are in the pdf file named breakouk.pdf <<<<<<<<<<<<<<<<<<<<<<<< 3145 Instructions: 1. Create a class named InterestCalculator 2. Add comments at the top of the Java file to convey the following information: /** @author Your Name @version 1.0 @since 02/01/2015 Purpose: Utilize programming concepts from Chapter 3 */ 3. Import the Scannerclass 4. Create a new Scannerclass object named keyboard to read keyboard input 5. Have the user enter their beginning principal balance (must be a double greater than zero). 6. If not a double greater than zero, have the user enter again. (Hint: Use a do-while loop) 7. Have the user enter their desired annual interest rate (must be a double greater than zero and less than 20%). 8. If not a double greater than zero and less than 20%, have the user enter again. (Hint: Use a do-while loop) 9. Have the user enter their desired number of quarters (must be an integer greater than zero or less than or equal to 40). ? 10. If not an integer greater than zero and less than or equal to 40, have the user enter again. (Hint: Use a do-while loop) 11. Display all of the information entered in steps 4-9. 12. Ask the user if all of the values are correct. If yes, proceed with step 12. If no, return to step 4. (Hint: Use a do-while loop) 13. For each quarter, calculate and display the beginning principal balance, the interest earned, and the final principal balance for the quarter using a for loop. Format the output to appear as U.S. currency with dollar sign and two digits to the right of the decimal. For example: The user entered 1000.00 for the beginning principal balance, 5.25 for the interest rate, and 8 for the number of quarters. The output from this part of the program should be similar to the following if all of the data is entered correctly the first time: I need help help with step 13. I have written the code for everything else but cannot seem to figure out how to make the for loop to get the chart. Can someone help? 3146 Instruction for the given code: First, we need to make an objective for the game. In the real game, numbers appear in random locations. The first player to occupy the square in which a number appears gets the points specified by the number. The following steps will add this feature: 1)In the game class, add data fields that will hold the position of the number square and its value. The value should start at 1 and increment every time a caterpillar catches it. 2)Modify the paint method in CaterpillarGame to display the number square, as well as the two caterpillars. 3)Create a method newNumberSquare to create a new, randomly distributed number value. Use the inPosition method provided by the two caterpillars to ensure that the number is not placed in a square already occupied by a caterpillar. Add a score data field to each caterpillar, to hold its current score. As part of advancing to a new position, have the caterpillar test the new position to see whether it is a scoring position. This can be most easily accomplished by adding a method squareScore to the class CaterpillarGame. This method will take as argument the new position offered by caterpillar. If the new position is not a scoring position, it will return zero. If it is a scoring position, it will return the score and call newNumberSquare to create a new scoring position. Add labels to the game window to display the two caterpillar scores. The two-player game now has scores but no simple way to end. In the original game, each caterpillar segment has a lifetime. This can be simulated by having each caterpillar maintain a counter A????1say, one that starts at 20 and counts down each step. Each time a score is made, the counter is reset to 20, and a new segment is added to the caterpillar. If the counter reaches 0, an extra segment is removed from the caterpillar, and the counter is reset to 20. when one of the caterpillars loses all its segments, the game is over. import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class Caterpillar { private Color color; private Point position; private char direction = 'E'; private Queue body = new LinkedList(); private Queue commands = new LinkedList(); 3147 Instruction bundle dependency checking has to be done in a static superscalar datapath. How many load-use cross-checks have to be done for a 4- way datapath? How many for a 8-way datapath? How many RAW intra-bundle dependency checks have to be done for a 4-way datapath? How many for a 8-way datapath? How many read and write ports does the RF have to have for a 4-way datapath? How many for a 8-way datapath? 3148 Insert your code in the file below where it says //Code this, then use the driver provided to test the program. Make a tree of integers //FILE TO USE: public class IntBSTree{ private class Node { private int data; private Node leftChild; private Node rightChild; public Node(int aData) { this.data = aData; this.leftChild = null; this.rightChild = null; } } private Node root; public IntBSTree() { root = null; } public void insert(int data) { //Code this } public void printInorder() { //Code this } public int getDepth(int value) { //Code this } } //DRIVER FOR TESTING IT: import java.util.*; public class IntBSTreeTester { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Int BST Tester!"); System.out.println("Creating tree"); IntBSTree testTree = new IntBSTree(); System.out.println("Populating Tree with values"); int[] valArr = {4,8,10,2,1,7,3,5,9,6}; for(int i : valArr) { testTree.insert(i); } System.out.println("Testing insertion by in-order traversal"); testTree.printInorder(); System.out.println("Getting depth of 6"); System.out.println(testTree.getDepth(6)); System.out.println("Getting depth of 14"); System.out.println(testTree.getDepth(14)); } } The class IntBSTree is given fill in the following methods insert: This method returns nothing and takes in an integer value that is then placed as a new node in the tree based on the binary tree properties. A reminder values greater than the parent go to the right subtree and values smaller go to the left subtree. Also it may be a good idea to use a recursive method in order to place these values. printInorder: This method which returns nothing and has no parameters prints the in order traversal of the tree. For in order traversal each left subtree must be visited, then the value is printed out, and finally each of the right subtrees is visited. It is a good idea to make a recursive method to assist with this. Also if done correctly in-order traversals print out each of the integers in ascending order. getDepth: The depth of a node is the number of edges from the root to that number. This method returns nothing and takes in a parameter corresponding to the integer value of a node whose depth is returned. If the value is not in the tree a -1 should be returned. Again a recursive helper method may be useful to solve this. Correct Print Out: Int BST Tester! Creating tree Populating Tree with values Testing insertion by in-order traversal 1 2 3 4 5 6 7 8 9 10 Getting depth of 6 4 Getting depth of 14 3149 Input data has lines organized as follows: column 1: character code for device (one of A, B, C, D, or E) columns 2-3: integer (device status code) columns 4-9: real value (measurement 1) columns 10-16: real value (measurement 2) Write a FORTRAN 90 program which reads this data from the keyboard (use the Unix redirect "<" with the data le). The program nds the following sums: A sum is found for each device. For devices with character codes "A", "B", "C" a calculation is done based on a low value and a high value for the device status code. If the status code is less than or equal to the low value then measurement 1 is added to the sum for the device. If the status code is greater than the low value and less than the high value, then measurement 2 is added to the sum for the device, otherwise the average of measurement 1 and 2 is added to the sum for the device. For devices with codes "D" and "E", just the low value is used and if the device status code is less than or equal to the low value, then measurement 1 is summed in , otherwise the average of measurements 1 and 2 is summed in. Additionally print neatly formatted (identical to the example below) output of the data read in. An example run with the program for this problem follows: $ cat dat1 B352.7842 4.125 C424.3354 -9.011 E872.2169 1.552 B233.0701-18.632 D621.7537 2.341 C430.2527 -8.303 E863.7962 -4.978 B252.3949 18.347 E903.4536 17.243 D742.8008-15.528 $ ./a.out B 35 2.7842 4.125 C 42 4.3354 -9.011 E 87 2.2169 1.552 B 23 3.0701 -18.632 D 62 1.7537 2.341 C 43 0.2527 -8.303 E 86 3.7962 -4.978 B 25 2.3949 18.347 E 90 3.4536 17.243 D 74 2.8008 -15.528 sumA= 0.00000000 sumB= 9.59000015 sumC= 4.58809996 sumD= -4.31624985 sumE= 11.6418495 A partial FORTRAN 90 program to accomplish the goals of this problem follows: !lab 3(a) solution by program lab3_a implicit none character ::code integer::ic integer :: InputStatus real :: sumA=0.0,sumB=0.0,sumC=0.0,sumD=0.0,sumE=0.0 real v1,v2,val integer:: low,high print *, "lab 3(a) solution by " do read(5," if( )exit write(*," select case (code) case('A') low=20; high=70 sumA=sumA+val case ('B') low=30; high=60 sumB=sumB+val case ('C') low=50; high = 90 sumC=sumC+val case ('D') low=50 sumD=sumD+val case ('E') low=30 sumE=sumE+val end do print *, "sumA=",sumA print *, "sumB=",sumB print *, "sumC=",sumC print *, "sumD=",sumD print *, "sumE=",sumE end program lab3_a 3150 "Inheritance and Polymorphism" Please respond to the following: Suppose that you are creating an enterprise application for storing the inventory for an automotive parts store. Describe one (1) way in which you would use inheritance in designing the application in question. Provide a rationale for your response. Using the same scenario in Part I of this discussion, provide one (1) example of a scenario or situation in which you would use polymorphism in designing the application in question. Justify your response 3152 The information below comes from the U.S.Energy Information Administration and indicates the net generation of electricity in 1000 MW - Hrs for the leading energy sources : Use shift - enter to enter the following data into Mathematica : for you to copy details: s = {{"Year", " all fuels", " coal", " natural gas", " nuclear", " conventional hydroelectric", " wind"}, {2013, 4.07`*^6, 1.58`*^6, 1.13`*^6, 789000.`, 269000.`, 168000.`}, {2012, 4.05`*^6, 1.51`*^6, 1.23`*^6, 769000.`, 276000.`, 141000.`}, {2011, 4.1`*^6, 1.73`*^6, 1.01`*^6, 790000.`, 319000.`, 120000.`}, {2010, 4.13`*^6, 1.85`*^6, 988000.`, 807000.`, 260000.`, 260000.`}, {2009, 3.95`*^6, 1.76`*^6, 921000.`, 799000.`, 273000.`, 73900.`}, {2008, 4.12`*^6, 1.99`*^6, 883000.`, 806000.`, 255000.`, 55400.`}, {2007, 4.16`*^6, 2.02`*^6, 897000.`, 806000.`, 248000.`, 34400.`}, {2006, 4.06`*^6, 1.99`*^6, 816000.`, 787000.`, 289000.`, 26600.`}, {2005, 4.06`*^6, 2.01`*^6, 761000.`, 782000.`, 270000.`, 17800.`}, {2004, 3.97`*^6, 1.98`*^6, 710000.`, 789000.`, 268000.`, 14100.`}, {2003, 3.88`*^6, 1.97`*^6, 650000.`, 764000.`, 276000.`, 11200.`}, {2002, 3.86`*^6, 1.93`*^6, 691000.`, 780000.`, 264000.`, 10400.`}, {2001, 3.74`*^6, 1.9`*^6, 639000.`, 769000.`, 217000.`, 6740.`}}; Show transcribed image text (i) Using the Table command, make a list that contains just the year, i.e, {2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001}. DO NOT TYPE THE LIST IN. Hint: You will need to use indices, i.e. s[[i]][[j]] to obtain the required information. (ii) Use the command Reverse, to have the list of years go in order. (i.e. Reverse[{a, b, c, d}] = {d, c, b, a}). (i) Using the Table command, make a list that contains just electricity from the wind. DO NOT TYPE THE LIST IN. (ii) Use the command Reverse, to reverse the list. With those two lists, make a clear, labelled bar chart of electricity generated from the wind. Find the mean and standard deviation for the electricity generated from the wind. Are mathematica's computation correct? Show your work, use numerical answers. (e) Using the results of part (d) prove that there has been a significant increase in the use of wind to generate electricity from 2001 to 2013. (f) Find the mean and standard deviation for electricity generated from all fuels (second column). Use numerical answers. (g) Using the results of part (f) decide if there has been a significant increase in the generation of electricity between 2001 and 2013. 3153 I have an industrial equipment which is controlled by a software. The software connects to it using sockets, and keeps the connection all the time alive, while from time to time sending commands to the equipment. Now, this equipment is represented by a class which encapsulates the sending and receiving of data. Next, I need to make a UI, that will show the state of the equipment, independent from the controlling software (controlling is on a different thread same solution). Refresh to the UI must be done lets say every second, but it can happen that UI wants to read data, and the controlling software wants to write. The problem is that the equipment might respond from 50 ms to 1 second, we don't know, and during the response no one must interfere! How can I best synchronize calls to the equipment communication class? There might be at least 2 solutions: Using simple lock(obj) {} statement in C#, for each method in the common. class Using events and a message queue with a subscriber concept While the first one might be simple, I assume for my case is the worst solution because it can block everything. The second one seems more OK, but the problem is that there will be for sure some delay on receiving the results if many subscribers are, or dunno, I'm not really sure. UPDATE: I implemented using simple lock. The reason is that some equipment do not have (some do, but most not), on their controller side, the possibility to process multiple request, and their buffer will overflow. So to make sure nothing bad happens, exclusive READ/WRITE lock is best solution I have found so far, and it works. 3154 Indicate whether overlfow occurs for each arithmetic operation Show transcribed image text The following binary numbers are in 2?s complement form. Perform the indicated arithmetic operations and verify the answers. (a) 100111+ 111001 (b)001011+ 100110 (C) 110001 -010010 (d) 101110-110111 Indicate whether overflow occurs for each computation. 3155 Indicate which predefined c ++types would most appropriately model each of the following : (please explain why) a.) information about a single product in an inventory-control program b.) the casualty figures for highway accidents in Texas from 1995-2005 c.) the casualty figures for highway accidents in each of the states from 1995-2005 d.) the casualty figures for highway accidents in each of the states subdivided by month 3156 Indicate which predefined c ++types would most appropriately model each of the following : (please explain why) a.) a chessboard b.) information about a single product in an inventory-control program c.) a list of famous quotations d.) the casualty figures for highway accidents in Texas from 1995-2005 e.) the casualty figures for highway accidents in each of the states from 1995-2005 f.) the casualty figures for highway accidents in each of the states subdivided by month g.)an electronic address book (name, address, and number) h.)a collection of hourly temperatures for a 24 hour period 3157 Index / Match Hi, I'm having problems using this function and NOt getting the dreaded #N/A retruned. Here we go.... On sheet1 I have drop downs in Cells A11, B11 & C11 based on lists. On sheet2 I have Data in Columns A,B,C & D. The drop downs in A11 equate to Column A, B11 to B and C11 to C. Column D has different values dependant on the combination of data in A-C. what I want is for Cell D11 on Sheet1 to show a value from Column D in Sheet 2 depending on the values entered in A11-C11. Can anybody help with the correct syntax?? Thanks !! 3158 Index / Match Hi, I'm having problems using this function and NOt getting the dreaded #N/A retruned. Here we go.... On sheet1 I have drop downs in Cells A11, B11 & C11 based on lists. On sheet2 I have Data in Columns A,B,C & D. The drop downs in A11 equate to Column A, B11 to B and C11 to C. Column D has different values dependant on the combination of data in A-C. what I want is for Cell D11 on Sheet1 to show a value from Column D in Sheet 2 depending on the values entered in A11-C11. Can anybody help with the correct syntax??? Thanks !! 3159 #include using namespace std; int main() { /* Lab 7 Comp201 Rewrite a previous project so that the comparison functions become operators and make month and day pointers to int. (no year). Start a new project or new file here! (main2.cpp?) (1) in class def: friend bool operator == (const DayOfYear& date1, const DayOfYear& date2); These are changed to operator overloads for <, >, >=, >= . friend bool lessThan(const DayOfYear& date1,const DayOfYear& date2); friend bool greaterThan(const DayOfYear& date1, const DayOfYear& date2); friend bool greaterThan_or_Equal(const DayOfYear& date1, const DayOfYear& date2); friend bool lessThan_or_Equal(const DayOfYear& date1, const DayOfYear& date2); (1a) Make the changes in definitions above and make signatures match BELOW MAIN. (Notice the const reference parameters.) (2) in class def change month and day from ints to pointers to int: int *month; int *day; (3) Change main() calls to reflect changes in the comparison functions to operators: change if (equals (today, bach_birthday) becomes: if ( today == bach_birthday) etc. (4) (see #8) Change default constructor to call new and use pointers : DayOfYear::DayOfYear() // default constructor { month = new int; // calls new *month = 1; //repeat for day day = new int; *day = 1; } (5) use of pointersd causes what changes here void DayOfYear::check_date( ) { if(day <=0 || day >31) {day = 1; month =1;} if (month <=0 || month >12) {day = 1; month =1;} } (6) add *'s void DayOfYear::input( ) { cout << "Enter the month as a number: "; cin >> *month; cout << "Enter the day of the month: "; cin >> *day; check_date(); } (7) add *'s void DayOfYear::output( ) { cout << "month = " << *month << ", day = " << *day << endl; } (8) Rewrite overload constructor to use new and references: DayOfYear::DayOfYear(int the_month, int the_day) { day = new int; Month = new int; *month = the_month; *day = the_day; check_date(); } (9) ALL IMPLEMENTIONS OF OPERATOR OVERLOADS GET DEREFERENCING bool operator == ( const DayOfYear& date1, const DayOfYear& date2) { return(*date1.month == *date2.month && *date1.day == *date2.day); } // do the rest (10) get_day and get_month get ref, deref int DayOfYear::get_day( ) { return *day; } int DayOfYear::get_month( ) { return *month; } void DayOfYear:: set_month(int new_month){ *month = new_month; } (11) write destructor DayOfYear::~DayOfYear() { delete day; delete month; } 3160 #include using namespace std; class Bank_Transaction { public: Bank_Transaction( ); //default constructor Bank_Transaction(double); double Check_Balance( ); void Deposit(double); void Withdrawal(double); private: double balance; }; Bank_Transaction::Bank_Transaction() { balance = 0; } Bank_Transaction::Bank_Transaction(double amount) { balance = amount; } double Bank_Transaction::Check_Balance() { return balance; } void Bank_Transaction::Deposit(double amount) { balance = balance + amount; } void Bank_Transaction::Withdrawal(double amount) { balance = balance - amount; } int main() { Bank_Transaction my_Acct; Bank_Transaction your_Acct(10340.85); cout<<"Your Account Balance = "< #include using namespace std; class Person { protected: string firstName; string lastName; public: Person(void) { cout<<"In Person's constructor -- A Derived Class"<>firstName; cout<<"Enter lastname: "; cin>>lastName; } string getFirstName(void) { return firstName; } string getLastName(void) { return lastName; } virtual void CalculateAndPrintPayrollInformation(void) { cout<<"This is Payroll Information for a Base Object"<>annual_salary; } float getSalary(void) { return annual_salary; } void CalculateAndPrintPayrollInformation(void) { cout<<"In Taxpayer's constructor -- A derived class of employe"<>hours_worked; cout<<"Enter hourly rate: "; cin>>hourly_rate; gross_pay = hours_worked * hourly_rate; income_tax = gross_pay * 0.25; net_pay = gross_pay - income_tax; cout<<"Gross Pay = "< #include using namespace std; class Person { protected: string firstName; string lastName; public: Person(void) { cout<<"In Person's constructor -- A Derived Class"<>firstName; cout<<"Enter lastname: "; cin>>lastName; } string getFirstName(void) { return firstName; } string getLastName(void) { return lastName; } }; class Employee : public Person { protected: float salary; public: Employee() { cout<<"In Employee's constructor -- A Derived Class"<>salary; } float getSalary(void) { return salary; } }; int main (void) { Employee Number_one; //calls Constructor of Person, then Constructor of employee Employee Number_two; //calls Constructor of Person, then Constructor of employee cout< #include #include using namespace std; // Complete function readPolynomial below. // // This function starts by asking the user for the order of the polynomial. // If the order entered is not between 1 and maxOrder, it will continue to ask // for the order, until a valid order is obtained. // Then it asks the user for the coefficient for the order (which cannot be 0), // followed by the coefficient for each power of x, down to 0. // It puts the coefficients in the polynomial array and returns the order // of the polynomial. int readPolynomial (int maxOrder, double polynomial[]) { // you should remove the "return 0;" once you have the function working return 0; } // Complete function displayPolynomial below. // // This function outputs the polynomial of order n in a nice format (as per // the sample executable). void displayPolynomial (int order, double polynomial[]) { } int main () { const int MAXN = 8; // maximum order (a constant) double polynomial[MAXN + 1]; int polynomialN; // read in the polynomial polynomialN = readPolynomial (MAXN, polynomial); // output message cout << "\nThe polynomial (order = " << polynomialN << ") is\n"; // followed by the polynomial displayPolynomial (polynomialN, polynomial); cout << endl; system("PAUSE"); return 0; } *C++ 3166 ** include a flawchart or UML and screenshot please. Temperature Statistics A file gives all of the temperatures for a period of time. Each number in the file is the temperature for 1 day. The number of days could be a month, a year, or the duration of a trip. You are to read in all of the temperatures from the file and print the following statistics: The number of days The temperature range, example: The temperatures ranged from -5 to 45 The average temperature The number of days (if any) that were freezing (32 degrees or less). Don't print if 0! The number of days (if any) that were 100 degrees or more. Don't print if 0! Example 1: The file contains these numbers: 20 15 32 40 37 Output: There were 5 days. The temperatures ranged from 15 to 40. The average temperature was 28.8 It was freezing on 3 days. Example 2: The file contains these numbers: 85 90 95 100 102 70 80 90 Output: There were 8 days. The temperatures ranged from 70 to 102. The average temperature was 89. It was 100 degrees or more on 2 days 3167 Improve the program by also outputting "The next higher weight is ___ with a cost of ___ cents". #include using namespace std; int main () { const int NUM_ELEMENTS = 14; // Number of elements double letterWeights[NUM_ELEMENTS]; // Weights in ounces int postageCosts[NUM_ELEMENTS]; // Costs in cents (usps.com 2013) double userLetterWeight = 0.0; // Letter weight bool foundWeight = false; // Found weight specified by user int i = 0; // Loop index // Populate letter weight/postage cost arrays letterWeights[i] = 1; postageCosts[i] = 46; ++i; letterWeights[i] = 2; postageCosts[i] = 66; ++i; letterWeights[i] = 3; postageCosts[i] = 86; ++i; letterWeights[i] = 3.5; postageCosts[i] = 106; ++i; letterWeights[i] = 4; postageCosts[i] = 152; ++i; letterWeights[i] = 5; postageCosts[i] = 172; ++i; letterWeights[i] = 6; postageCosts[i] = 192; ++i; letterWeights[i] = 7; postageCosts[i] = 212; ++i; letterWeights[i] = 8; postageCosts[i] = 232; ++i; letterWeights[i] = 9; postageCosts[i] = 252; ++i; letterWeights[i] = 10; postageCosts[i] = 272; ++i; letterWeights[i] = 11; postageCosts[i] = 292; ++i; letterWeights[i] = 12; postageCosts[i] = 312; ++i; letterWeights[i] = 13; postageCosts[i] = 332; ++i; // Prompt user to enter letter weight cout << "Enter letter weight (in ounces): " << endl; cin >> userLetterWeight; // Postage costs is based on smallest letter weight greater than // or equal to mailing letter weight foundWeight = false; for (i = 0; (i < NUM_ELEMENTS) && (!foundWeight); ++i) { if( userLetterWeight <= letterWeights[i] ) { foundWeight = true; cout << "Postage for USPS first class mail is "; cout << postageCosts[i] << " cents" << endl; } } if( !foundWeight ) { cout << "Letter is too heavy for USPS first class mail." << endl; } return 0; } 3168 import java.util.Scanner; public class Main { static final int LIMIT = 7; public static void main(String[] args) { // TODO Auto-generated method stub int[] play = new int[LIMIT]; int num, i = 0; do { System.out .print("please enter an integer between 1-49, inclusive: "); Scanner in = new Scanner(System.in); num = in.nextInt(); if(num > 0 && num < 50 && $1$){ $2$; i++; } } while ($3$); System.out.println("your number are: "); for (int j = 0; j < LIMIT; j++){ System.out.prinf("%-3d", play[j]); } } private static boolean isTaken(int[] play, int num){ for( int i = 0; i < LIMIT; i++){ boolean $4$; if ($4$){ $5$; } } $6$; } } from the code above match up each statement: !isTaken(play, num) 1. $1$ return false 2. $2$ i5->6->3 1, 9 // Add a 9 at the front of the linked-list. After this operation the linked-list should be: 9->4->5->6->3 2, 1 // Add a 1 at the end of the linked-list. After this operation the linked-list should be: 9->4->5->6->3->1 3, // Delete the first node in the linked-list. After this operation the linked-list should be: 4->5->6->3->1 4, // Delete the last node in the linked-list. After this operation the linked-list should be: 4->5->6->3 5, 11 // Delete the node with the value 11 in it. Since this is not possible, it should print "N/A" 5, 6 // Delete the node with the value 6 in it. After this operation the linked-list should be: 4->5->3 Note: with an empty linked-list, trying to delete from the front and/or end, should print "N/A" in the console 3172 Implement the recursive factorial function given below (from the lecture notes on recursion). Develop a main program that allows the user to enter any integer (positive) integer value, and displays the factorial of that value. The program should allow the user to either keep entering another value, or quit the program. public static int factorial(int n) { if (n == 0) return (1); else return (n * factorial(n?1)); 3173 Implement a program named Rectangle that calculates the area using variable name getArea, getLength, and getWidth. Display the area of the Rectangle PYTHON PROGRAMMING ONLY 3174 implement an in-place heap sort program ruby. The program should have a function/procedure/subroutine that will do the main work. That is, to accept a list/array (or anything appropriate) of integers and then sort it using the in-place heap sort algorithm. The heap sort algorithm requires converting the list/array into a heap. Once the list/array is converted into a heap, you need to print out the heap in tree-format as a string before continuing. This function/procedure/subroutine should return the sorted list/array and the string if possible. let the sorted list/array to be return via A????1outA????1 parameter (or pass by reference). the program should also have a main function that allows you to read data from a file (so you can sort different list/array). 3175 Implement linear regression calculations using VBA and compare your results against built-in functions in Excel for the data in Problem 17.25. 17.25) The following data show the relationship between the viscosity of SAE 70 oil and temperature. After taking the log of the data, use linear regression to find the equation of the line that best fits the data and the r2 value. Temparture Viscosity 26.67 1.35 93.33 .085 148.89 .012 315.56 .0007 3176 Implement an illegal memory address instruction in the multicycle datapath. Your answer must include the following a) Figure of the multi-cycle datapath with all of the modifications clearly marked. b) Assume a sequencer implementation with a ROM. 1. Show updates to the controller ROM 2. Updates to the dispatch tables 3. Any other additions as necessary c) Explain in a few sentences how the implementation will work. Show transcribed image text Implement an illegal memory address instruction in the multicycle datapath. Your answer must include the following a) Figure of the multi-cycle datapath with all of the modifications clearly marked. b) Assume a sequencer implementation with a ROM. 1. Show updates to the controller ROM 2. Updates to the dispatch tables 3. Any other additions as necessary c) Explain in a few sentences how the implementation will work. 3177 Implement the following function as a new function for the linked list toolkit. (Use the usual node definition with member variables called data and link as defined above.) bool all_42s(const node* head_ptr); // Precondition: head_ptr is the head pointer of a linked list. // The list might be empty or it might be non-empty. // Postcondition: The return value is true if every node in the // list contains 42 in the data part. NOTE: If the list is empty, // then the function returns true. 3178 Implement the following function as a new function for the linked list toolkit. (Use the usual node definition with member variables called data and link as defined above.) size_t count_42s(const node* head_ptr); // Precondition: head_ptr is the head pointer of a linked list. // The list might be empty or it might be non-empty. // Postcondition: The return value is the number of occurrences // of 42 in the data field of a node on the linked list. // The list itself is unchanged. 3179 Implement a dummy verification protocol on top of UDP/IP/ETH protocol stack. In this protocol, the client sends a 32-bit nonce in network byte order as payload of an UDP message to server; the server increments nonce by one and returns the reply to client. In order not to conflict with the existing TCP/IP stack operation, you can use the Ethernet payload type of 0x88b5 for demultiplexing purposes. Build the client and server applications. Use packet sockets in Linux to send/receive Ethernet frames. 3180 Implement the "count_ones" function that counts the number of "1" bits in the binary representation of an integer, and returns the result. unsigned int count_ones(unsigned int x) { __asm{ push ebx push ecx push edx push esi push edi // BEGIN YOUR CODE HERE // END YOUR CODE HERE pop edi pop esi pop edx pop ecx pop ebx } } 3181 Implement copyAll which will go through the whole data structure pointed to by root and copy it correctly. You should not access freed heap contents so the order of deleting matters. Write your recursive solution as consise and cleas as possible. you do not need helpter functions. typedef struct keyNodeStruct{ char *key; valueNode *values; struct keyNodeStruct *next; }keyNode; typedef struct valueNodeStruct { char *value; struct valueNodeStruct *next; }valueNode; void delAll(tree *root) { // Recursion 3182 You are to implement 2 different hash tables, with different hashing functions. All of them should implement the following interface: public interface HashTable,V> { public void add(K key, V value); public V remove(K key); public V lookup(K key); public V[] getSortedList(V[] list); public void printReport(); }  The printReport() method should print to the console the following statistics: The Load Fator, that is, the ratio of used to total number of buckets.  The longest chain in the table, that is, the maximum number of collisions for a particular bucket.  The Density Factor, that is, the ratio of elements stored elements to total number of buckets.  The Chanining Factor, that is, the average length of any chain in the table. The 2 types of hashing functions you are to implement are:  Additive Hashing  XOR-Shift (Rotational) Hashing The hash tables should implement resizing and rehashing. The V[] getSortedList(V[] list) method should return a sorted list with all the elements in the array. You will use a stack and a queue to implement a scambled version of the rotational hashing function. Before applying the rotational hash to the string, you will implement a function that will scramble the characters in the string so that every 3 successive characters in the string are inverted. For example, if the string to be hashed is "Jonathan", then the function should turn the string into "noJhtana" before applying the rotational hash. This function can be easily implemented using a stack and a queue. Now that you've implemented the hash tables you will use to implement a ver simple registry for students' records. You will create a class to keep student's information: name, student ID, and grade. The program will have the following functionality:  The record is persistent, that is, the whole registry should be saved on file upon exiting the program, and after any major change.  The program should provide the option to create a new entry with a student's name, ID, and grade.  There should be an option to lookup a student from his student ID (this will be the key in the hash table).  There should be an option to remove a particular entry by providing the student ID.  There should be an option to display the whole registry, sorted by student ID. Remember that the registry must be persistent, so you will have to save all this information to the file system. You may use any of the versions of hash tables implemented in the previous exercise. 3183 You are to implement 2 different hash tables, with different hashing functions. All of them should implement the following interface: public interface HashTable,V> { public void add(K key, V value); public V remove(K key); public V lookup(K key); public V[] getSortedList(V[] list); public void printReport(); }  The printReport() method should print to the console the following statistics: The Load Fator, that is, the ratio of used to total number of buckets.  The longest chain in the table, that is, the maximum number of collisions for a particular bucket.  The Density Factor, that is, the ratio of elements stored elements to total number of buckets.  The Chanining Factor, that is, the average length of any chain in the table. The 2 types of hashing functions you are to implement are:  Additive Hashing  XOR-Shift (Rotational) Hashing The hash tables should implement resizing and rehashing. The V[] getSortedList(V[] list) method should return a sorted list with all the elements in the array. You will use a stack and a queue to implement a scambled version of the rotational hashing function. Before applying the rotational hash to the string, you will implement a function that will scramble the characters in the string so that every 3 successive characters in the string are inverted. For example, if the string to be hashed is "Jonathan", then the function should turn the string into "noJhtana" before applying the rotational hash. This function can be easily implemented using a stack and a queue. Now that you've implemented the hash tables you will use to implement a ver simple registry for students' records. You will create a class to keep student's  information: name, student ID, and grade. The program will have the following functionality: The record is persistent, that is, the whole registry should be saved on file upon exiting the program, and after any major change.  The program should provide the option to create a new entry with a student's name, ID, and grade.  There should be an option to lookup a student from his student ID (this will be the key in the hash table).  There should be an option to remove a particular entry by providing the student ID.  There should be an option to display the whole registry, sorted by student ID. Remember that the registry must be persistent, so you will have to save all this information to the file system. You may use any of the versions of hash tables implemented in the previous exercise. 3184 image in high quality http://www.mediafire.com/view/vw7wo6kvqfbjupx/IMG_0254.JPG http://www.mediafire.com/view/ha9d39l4qdxoel1/IMG_0255.JPG# code http://www.mediafire.com/view/ec5ivq0eil49os4/Trial.h http://www.mediafire.com/view/4axqziute07h684/main.cpp csv file http://www.mediafire.com/view/p43hz6xc25aanu8/results.csv 3185 Im building this website for a small store and I was told that its better not to keep the login and the rest of the users information on the same table. Now im wondering, what is the best way to implement this website's database? Some of the database tables are: Customers Providers Products Etc.. I need to have different users, after someone is logged in the site, depending on their rights they can do a series of things: If they are a customer they can order stuff If they are employees they can order stuff, manage stock, add customers, etc If they are the owner or administrator they can add employees and everything else. Should I keep the login and the rest of the information of the user in the same table? 3186 Identify whether each of the following statement applies to a ring topology, star topology, or both: A????1 * Use copper wire twisted pair cable. A????1 * The data flows in one direction. A????1 * If the cable breaks, the network is down. A????1 * It's the most common topology. A????1 * Each device is connected to the central hub with its own cable. * Easily add more workstations and maintenance. 3187 Identify whether each of the following statement applies to a ring topology, star topology, or both. 1.Use copper wire twisted pair cable. 2.The data flows in one direction. 3.If the cable breaks, the network is down. 4.ItA????1s the most common topology. 5.Each device is connected to the central hub with its own cable. 6.Easily add more workstations and maintenance. 3188 Identify why information cleansing is critical to California Pizza KitchenA????1s business intelligence tools success 3189 Identify and describe three security issues related to cloud computing. Recommend countermeasures to mitigate or prevent these issues from becoming a security risk. 3190 http://www.informationweek.com/it-life/geekend-the-ethics-of-making-robots-like-people/a/d-id/1316716 Researchers are progressing toward creating a system that can pass the Turing test, a test that bestows A????1thinkingA????1 status on a machine that passes by fooling 30% of its human interrogators in a series of five-minute keyboard conversations. We must ask if itA????1s ethical to fool humans into believing that such systems are human. The article focuses on several possible scenarios, but limit your discussion to the issue of this question. Examine briefly the advantages of such a robot as described, then decide whether it is ethical to build such a robot. 3191 http://www.informationweek.com/applications/google-wins-book-scanning-case/d/d-id/1112240 At the end of last year, Google was finally able to extricate itself from legal entanglements regarding its copying of texts in order to make them accessible through search queries. It did so without asking the authors. As the article details, one of the suits was settled out of court while the other was decided in favor of Google last November. The judge cited "significant public benefits" after having been encouraged by the court of appeals to reconsider, according to the principles of fair use, his previous decision. The Authors Guild obviously disagreed. In approximately 300 words, choose a side and argue for that side. 3192 http://pastebin.com/ZHAKkt8r currently, the "mergesort" section at the bottom uses an insertion sort algorithm. modify the code in the bottom section so that "mergesort" actually uses a mergesort algorithm 3193 http://imgur.com/A3X8CWn Please help me correct my program or write one that i can edit SOURCE CODE: /* Donald Krambeck Homework 4 My program inputs the values of the grade[] array, and calculates the total and avarage. It then displays the value of the total, average, and the grades. */ #include using namespace std; int main() { double grade[100]; //double data type array double total = 0, avg = 0; // double data type variables int i, count = 0; //int data type array cout << " Please enter the values of grades " << endl; //display output for (i = 0; grade[i]; != '\0'; i++) //loop to input values { cin >> grade[i]; } if (grade[i] > 0) //condition to check negative values { total = total + grade[i]; //counts total of grades count++; //increase the counter by one } else { break; //break from loop } avg = total / count; //calculates the average cout << " The total of all the grades is " << total << endl; cout << " The average of all the grades is " << avg << endl; cout << "The grades below average are " << endl; for (i = 0; i < count; i++) //loop to find grades below average { if (grade[i] < avg) //condition to find grades below average { cout << " * " << grade[i] << endl; } } for (i = 0; i < count; i++) //find equivalent letter for the grade { if (grade[i] < 60) //find equivalent letter for the grade { cout << grade[i] << " = F " << endl; } else if (grade[i] >= 60 && grade[i] < 70) //find equivalent letter for the grade { cout << grade[i] << " = D " << endl; } else if (grade[i] >= 70 && grade[i] < 80) //find equivalent letter for the grade { cout << grade[i] << " = C " << endl; } else if (grade[i] >= 80 && grade[i] < 90) //find equivalent letter for the grade { cout << grade[i] << " = B " << endl; } else if (grade[i] >= 90 && grade[i] < 100) //find equivalent letter for the grade { cout << grade[i] << " = A " << endl; } } return 0; } 3194 html Show transcribed image text This assignment must include: ? ONE grid-based page. ? Appropriate selection and use of color, typography and images to establish the personality of the page. ? At least five links with appropriately styled pseudo-classes (link, visited, hover, active). ? Use of semantic html tags, classes and ids ? An EXTERNAL css style sheet Part I: Create a grid-based website! Use Blueprint to create a one-page grid-based website. The topic of the website A???s your choice. 3195 My hp restarts itself automatically to update all of the time. I can not figure out how to make it stop doing this. I was working on a matlab project and fell asleep. My computer restarted and what I had been working on didn't get saved. Is there any way to restore it? I have been working for the past 6 hours and lost everything and I do not remember what I did. 3196 Howto Concatenate vertical values with one criteria? I have the following problem: I have records and I want to get a string of text as a result(column K) using column J as my criteria(unique list from "A") out of column G. How can I do this? Thanks A 1 B C D E F G text 1 H I J K 1 text1text2 1 text 2 2 text3 2 text 3 3 text4text5 3 text 4 4 text6 3 text 5 4 text 6 Thanks for help !! 3197 Host X and Y are communicating over a TCP connection, and Host Y has already received from X all bytes up through byte 1024. Suppose Host X then sends 2 segments to Host Y back-to-back. The 1st and 2nd segments contain 70 and 20 bytes of data, respectively. In the 1st segment, the sequence number is 1025, the source port number is 17226, and the destination port number is 80. Host Y sends an acknowledgement whenever it receives a segment from Host X. a) In the 2nd segment sent from Host X to Y, what are the sequence number, source port number, and destination port number? b) If the first segment arrives before the second segment, in the acknowledgement of the 1st arriving segment, what is the acknowledgment number, the source port number, and the destination port number? c) If the second segment arrives before the 1st segment, in the acknowledgement of the 1st arriving segment, what is the acknowledgment number? 3198 I hope this question gives some interesting answers because it's one that's bugged me for a while. Is there any real value in unit testing a controller in ASP.NET MVC? What I mean by that is, most of the time, (and I'm no genius), my controller methods are, even at their most complex something like this: public ActionResult Create(MyModel model) { // start error list var errors = new List(); // check model state based on data annotations if(ModelState.IsValid) { // call a service method if(this._myService.CreateNew(model, Request.UserHostAddress, ref errors)) { // all is well, data is saved, // so tell the user they are brilliant return View("_Success"); } } // add errors to model state errors.ForEach(e => ModelState.AddModelError("", e)); // return view return View(model); } Most of the heavy-lifting is done by either the MVC pipeline or my service library. So maybe questions to ask might be: what would be the value of unit testing this method? would it not break on Request.UserHostAddress and ModelState with a NullReferenceException? Should I try to mock these? if I refractor this method into a re-useable "helper" (which I probably should, considering how many times I do it!), would testing that even be worthwhile when all I'm really testing is mostly the "pipeline" which, presumably, has been tested to within an inch of it's life by Microsoft? I think my point really is, doing the following seems utterly pointless and wrong [TestMethod] public void Test_Home_Index() { var controller = new HomeController(); var expected = "Index"; var actual = ((ViewResult)controller.Index()).ViewName; Assert.AreEqual(expected, actual); } Obviously I'm being obtuse with this exaggeratedly pointless example, but does anybody have any wisdom to add here? Looking forward to it... Thanks. 3199 homework questions 1) What is the main reason to use the 3-way Quicksort? In other words: in which situation is the 3-way Quicksort significantly faster than the 'traditional' quicksort? 2) The Euclidean algorithm is an effective way to calculate the greatest common divisor (gcd) Complete the sentence below based on the method gcd 00 int gcd (int a, int b) 01 { 02 if (b == 0) 03 return a; 04 else 05 return gcd(b, a % b); 06 } The base case is in line: a) 03 b) 05 c) 03 and 05 d) 00 the recursive case is in line: a) 03 b) 05 c) 03 and 05 d) 00 3) Assume you enter the following data in the order presented to create a Binary Search Tree: PNOQM Which of the trees is created? Show transcribed image text 1)What is the main reason to use the 3-way Quicksort? In other words: in which situation is the 3-way Quicksort significantly faster than the 'traditional' quicksort? 2)The Euclidean algorithm is an effective way to calculate the greatest common divisor (gcd) Complete the sentence below based on the method gcd The base case is in line: a) 03 b) 05 c) 03 and 05 d) 00 the recursive case is in line: a) 03 b) 05 c) 03 and 05 d) 00 3)Assume you enter the following data in the order presented to create a Binary Search Tree: Which of the trees is created? 3200 Homework Help Show transcribed image text For this homework (Hwk06- Re-stocking Xumarts Inventory). we will use for-loops to re-stock XuMart's inventory. 3201 For this homework you will continue the pm1::Vector class that we started in lecture 10. It may look like a lot of work, but most of these functions should onl be a line or two of code and quite a few simply call one of the other functions. You will add the following functions to the class: //Constructor with an initial size and value (5%) Vector(unsigned int initial_size, int initial_value); //Functions to check the number of elements (5% each for 10%) //Returns true if the container is empty, false otherwise bool pm1::Vector::empty(); //Returns the number of elements in the container unsigned int pm1::Vector::size(); //Functions to modify the the container (10% for each for 50%) //Remove all elements from the container void pm1::Vector::clear(); //Insert value before the specified location //If the value is out of range, throw a std::out_of_range exception //Note that the end() location is valid; this is the same as push_back void pm1::Vector::insert(pm1::Vector::iterator location, int value); //Remove the value at the specified location //If the value is out of range, throw a std::out_of_range exception void pm1::Vector::erase(pm1::Vector::iterator location); //Insert the given value at the end of the container void pm1::Vector::push_back(int value); //Remove the value at the end of the container //If the container is empty, throw a std::out_of_range exception void pm1::Vector::pop_back(); HINT! At times you will need to make the array bigger. To do that, this private member function is provided to you: void pm1::Vector::increaseSize() { //Make the new, larger array int* bigger = new int[mem_size_*2]; //Copy over the existing data for (int i = 0; i < size_; ++i) { bigger[i] = data_[i]; } //The available memory size is now doubled mem_size_ *= 2; //Delete the old array delete[] data_; //Set the pointer to the new array data_ = bigger; } You do not need to bother making the array smaller, even if all of the data is removed with the clear() function. The insert member function is the most tricky, so you have been given half of the code for it. The equality operator is given to you, and you will implement the rest: //Comparison operators. These will compare elements of the vector one by one. bool operator==(pm1::Vector& a, pm1::Vector& b) { //They are not equal if the size is different //or if any element does not match if (a.size() != b.size()) { return false; } else { for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return false; } } } //Otherwise the two vectors are equal return true; } //Comparison operators. These will compare elements of the vector one by one. //(5% for each working operator) bool operator!=(pm1::Vector& a, pm1::Vector& b); bool operator<(pm1::Vector& a, pm1::Vector& b); bool operator<=(pm1::Vector& a, pm1::Vector& b); bool operator>(pm1::Vector& a, pm1::Vector& b); bool operator>=(pm1::Vector& a, pm1::Vector& b); Thats the question and the two files referenced are #include "pm1vector.h" #include //The null constructor pm1::Vector::Vector() { //Assume that the user will want to hold at least a few values //This saves us from constantly allocating new memory data_ = new int[10]; mem_size_ = 10; //Nothing stored yet size_ = 0; } pm1::Vector::Vector(unsigned int initial_size) { if (0 == initial_size) { size_ = 0; mem_size_ = 0; //Mark the memory as invalid data_ = nullptr; } else { data_ = new int[initial_size]; mem_size_ = initial_size; size_ = initial_size; } } //Destructor pm1::Vector::~Vector() { //Delete the data if there is any allocated if (0 != mem_size_) { delete[] data_; } } int& pm1::Vector::operator[](unsigned int offset) { //Notice that c++ knows we want to return a reference //No special syntax is required return data_[offset]; } int& pm1::Vector::at(unsigned int offset) { if (offset >= size_) { //Stops the function and throws an exception throw std::out_of_range("vector index out of range"); } return data_[offset]; } pm1::Vector::iterator pm1::Vector::begin() { //The first position in the vector return data_; } pm1::Vector::iterator pm1::Vector::end() { //One beyond the last valid position return data_ + size_; } void pm1::Vector::increaseSize() { //Make the new, larger array //Handle the case where the array started empty (nothing to copy or delete) if (0 == mem_size_) { mem_size_ = 10; data_ = new int[mem_size_]; } else { //Otherwise the available memory size is now doubled mem_size_ *= 2; int* bigger = new int[mem_size_]; //Copy over the existing data for (int i = 0; i < size_; ++i) { bigger[i] = data_[i]; } //Delete the old array delete[] data_; //Set the pointer to the new array data_ = bigger; } } //Insert value before the specified location //If the value is out of range, throw a std::out_of_range exception //Note that the end() location is valid; this is the same as push_back void pm1::Vector::insert(pm1::Vector::iterator location, int value) { if (begin() > location or end() < location) { //Stops the function and throws an exception throw std::out_of_range("insert location is out of range"); } //First see if there is enough space if (size_+1 > mem_size_) { //If we increase the size of the vector then the previous //location pointer isn't value since we deleted the older, smaller array //Remember its offset and find the new iterator location after //increasing the array size int offset = std::distance(begin(), location); increaseSize(); location = data_ + offset; } //TODO You must finish this function //You'll need to increase the size and shift all of the elements //from location to end() over by one position, and copy value //into the given location } //Comparison operators. These will compare elements of the vector one by one. //This operator is given as an example to do the rest bool operator==(pm1::Vector& a, pm1::Vector& b) { //They are not equal if the size is different //or if any element does not match if (a.size() != b.size()) { return false; } else { for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return false; } } } //Otherwise the two vectors are equal return true; } and //Use a name (PM1VECTOR_H_) to check if this file was //already included. If the name isn't defined, then //define it and create the class #ifndef PM1VECTOR_H_ #define PM1VECTOR_H_ namespace pm1 { //This vector will only hold ints for now class Vector { public: //Name int* iterator so that the name Vector::iterator exists typedef int* iterator; //Null constructor to create an empty vector Vector(); //Constructor with an initial size Vector(unsigned int initial_size); //Destructor that frees any allocated memory ~Vector(); //Array operator for element access int& operator[](unsigned int offset); //At function for element access int& at(unsigned int offset); //Fetch the first iterator iterator begin(); //Fetch the last iterator iterator end(); private: //We'll put underscores after private variable names to help us //tell them apart from other variables //A pointer to the actual data int* data_; //How large is the array? unsigned int mem_size_; //How many element are currently being held? unsigned int size_; //Doubles the allocated space, copies old array to the new one, and //deletes the old array void increaseSize(); }; } //End the preprocessor guard from before #endif 3202 OCopy and paste your question here...Write the definition of the member function print that prints the contents of u and w. f. Write the definition of the default 3203 For this homework you will continue the pm1::Vector class that we started in lecture 10. It may look like a lot of work, but most of these functions should onl be a line or two of code and quite a few simply call one of the other functions. You will add the following functions to the class: //Constructor with an initial size and value (5%) Vector(unsigned int initial_size, int initial_value); //Functions to check the number of elements (5% each for 10%) //Returns true if the container is empty, false otherwise bool pm1::Vector::empty(); //Returns the number of elements in the container unsigned int pm1::Vector::size(); //Functions to modify the the container (10% for each for 50%) //Remove all elements from the container void pm1::Vector::clear(); //Insert value before the specified location //If the value is out of range, throw a std::out_of_range exception //Note that the end() location is valid; this is the same as push_back void pm1::Vector::insert(pm1::Vector::iterator location, int value); //Remove the value at the specified location //If the value is out of range, throw a std::out_of_range exception void pm1::Vector::erase(pm1::Vector::iterator location); //Insert the given value at the end of the container void pm1::Vector::push_back(int value); //Remove the value at the end of the container //If the container is empty, throw a std::out_of_range exception void pm1::Vector::pop_back(); HINT! At times you will need to make the array bigger. To do that, this private member function is provided to you: void pm1::Vector::increaseSize() { //Make the new, larger array int* bigger = new int[mem_size_*2]; //Copy over the existing data for (int i = 0; i < size_; ++i) { bigger[i] = data_[i]; } //The available memory size is now doubled mem_size_ *= 2; //Delete the old array delete[] data_; //Set the pointer to the new array data_ = bigger; } You do not need to bother making the array smaller, even if all of the data is removed with the clear() function. The insert member function is the most tricky, so you have been given half of the code for it. The equality operator is given to you, and you will implement the rest: //Comparison operators. These will compare elements of the vector one by one. bool operator==(pm1::Vector& a, pm1::Vector& b) { //They are not equal if the size is different //or if any element does not match if (a.size() != b.size()) { return false; } else { for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return false; } } } //Otherwise the two vectors are equal return true; } //Comparison operators. These will compare elements of the vector one by one. //(5% for each working operator) bool operator!=(pm1::Vector& a, pm1::Vector& b); bool operator<(pm1::Vector& a, pm1::Vector& b); bool operator<=(pm1::Vector& a, pm1::Vector& b); bool operator>(pm1::Vector& a, pm1::Vector& b); bool operator>=(pm1::Vector& a, pm1::Vector& b); Thats the question and the two files referenced are #include "pm1vector.h" #include //The null constructor pm1::Vector::Vector() { //Assume that the user will want to hold at least a few values //This saves us from constantly allocating new memory data_ = new int[10]; mem_size_ = 10; //Nothing stored yet size_ = 0; } pm1::Vector::Vector(unsigned int initial_size) { if (0 == initial_size) { size_ = 0; mem_size_ = 0; //Mark the memory as invalid data_ = nullptr; } else { data_ = new int[initial_size]; mem_size_ = initial_size; size_ = initial_size; } } //Destructor pm1::Vector::~Vector() { //Delete the data if there is any allocated if (0 != mem_size_) { delete[] data_; } } int& pm1::Vector::operator[](unsigned int offset) { //Notice that c++ knows we want to return a reference //No special syntax is required return data_[offset]; } int& pm1::Vector::at(unsigned int offset) { if (offset >= size_) { //Stops the function and throws an exception throw std::out_of_range("vector index out of range"); } return data_[offset]; } pm1::Vector::iterator pm1::Vector::begin() { //The first position in the vector return data_; } pm1::Vector::iterator pm1::Vector::end() { //One beyond the last valid position return data_ + size_; } void pm1::Vector::increaseSize() { //Make the new, larger array //Handle the case where the array started empty (nothing to copy or delete) if (0 == mem_size_) { mem_size_ = 10; data_ = new int[mem_size_]; } else { //Otherwise the available memory size is now doubled mem_size_ *= 2; int* bigger = new int[mem_size_]; //Copy over the existing data for (int i = 0; i < size_; ++i) { bigger[i] = data_[i]; } //Delete the old array delete[] data_; //Set the pointer to the new array data_ = bigger; } } //Insert value before the specified location //If the value is out of range, throw a std::out_of_range exception //Note that the end() location is valid; this is the same as push_back void pm1::Vector::insert(pm1::Vector::iterator location, int value) { if (begin() > location or end() < location) { //Stops the function and throws an exception throw std::out_of_range("insert location is out of range"); } //First see if there is enough space if (size_+1 > mem_size_) { //If we increase the size of the vector then the previous //location pointer isn't value since we deleted the older, smaller array //Remember its offset and find the new iterator location after //increasing the array size int offset = std::distance(begin(), location); increaseSize(); location = data_ + offset; } //TODO You must finish this function //You'll need to increase the size and shift all of the elements //from location to end() over by one position, and copy value //into the given location } //Comparison operators. These will compare elements of the vector one by one. //This operator is given as an example to do the rest bool operator==(pm1::Vector& a, pm1::Vector& b) { //They are not equal if the size is different //or if any element does not match if (a.size() != b.size()) { return false; } else { for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return false; } } } //Otherwise the two vectors are equal return true; } and //Use a name (PM1VECTOR_H_) to check if this file was //already included. If the name isn't defined, then //define it and create the class #ifndef PM1VECTOR_H_ #define PM1VECTOR_H_ namespace pm1 { //This vector will only hold ints for now class Vector { public: //Name int* iterator so that the name Vector::iterator exists typedef int* iterator; //Null constructor to create an empty vector Vector(); //Constructor with an initial size Vector(unsigned int initial_size); //Destructor that frees any allocated memory ~Vector(); //Array operator for element access int& operator[](unsigned int offset); //At function for element access int& at(unsigned int offset); //Fetch the first iterator iterator begin(); //Fetch the last iterator iterator end(); private: //We'll put underscores after private variable names to help us //tell them apart from other variables //A pointer to the actual data int* data_; //How large is the array? unsigned int mem_size_; //How many element are currently being held? unsigned int size_; //Doubles the allocated space, copies old array to the new one, and //deletes the old array void increaseSize(); }; } //End the preprocessor guard from before #endif 3204 Homework 8 The following code is a C++ example of a very limited implementation of a Linked List. It is written as a class wrapper for a Node structure and the functions to create a list, add values, and show the contents. Also note the destructor will eliminate the list elements from memory. 1. class List { 2. struct Node { 3. int data; 4. Node * next; 5. }; 6. 7. Node * head; 8. 9. public: 10. List() { 11. head = NULL; 12. } 13. 14. ~List() { // delete the list 15. while(head != NULL) { 16. Node * n = head->next; 17. delete head; 18. head = n; 19. } 20. } 21. 22. void add(int value) { 23. Node * n = new Node; 24. n->data = value; 25. n->next = head; 26. head = n; 27. } 28. 29. void show(){ 30. while(head !=NULL) { 31. Node * n = head->next; 32. cout<< head->data <<", "; 33. head = n; 34. } 35. cout << endl; 36. } 37. 38. }; 39. Illustration 1: Linked List Class Illustration 2 is a main program which adds 7 values to the list and then shows the contents. 40. int main() { 41. List MyList; 42. 43.MyList.add(5); 44.MyList.add(12); 45.MyList.add(24); 46.MyList.add(32); 47.MyList.add(47); 48.MyList.add(54); 49.MyList.add(65); 50. 51.MyList.show(); 52. return 0; 53.} Illustration 2: Step 1. Main function Step 1. Put the two pieces of code together in a Code::Blocks C++ console application and run the program to print out the results. Screen capture the output and turn for Step 1. Note: #include <> statements for libraries will have to be added plus A????1using std::A????1 declarations. Question 1. Why does the data print out in the sequence that it does? Step 2. Modify the List class in Illustration 1 to be a templated class. Use the 'template' keyword to allow the class to accept any type of data for the list. Then use the following code for the main function and print out results. Screen capture the output and turn in for Step 2. 54. int main() 55.{ 56. // create first list 57. List MyList; 58. 59.MyList.add(5); 60.MyList.add(12); 61.MyList.add(24); 62.MyList.add(32); 63.MyList.add(47); 64.MyList.add(54); 65.MyList.add(65); 66. 67. cout << "Here is my first list " << endl; 68. MyList.show(); 69. 70. // Create second list 71. List MyStringList; 72. 73.MyStringList.add("First String"); 74.MyStringList.add("Second String"); 75.MyStringList.add("Third String"); 76.MyStringList.add("Fourth String"); 77.MyStringList.add("Fifth String"); 78. 79. cout << "Here is my Second list " << endl; 80.MyStringList.show(); 81. return 0; 82.} Illustration 3: Step 2. Main function Reference: http://stackoverflow.com/questions/397895/how-could-i-create-a-list-in-c 3205 Homework 7 Write a C++ console program to do the following: 1. Define an array of ints with the ten elements { 0, 1,2,3, 4, 5, 6, 7, 8, 9 }. 2. Define a vector with those ten elements. 3. Define a list with those ten elements. 4. Define a second array, vector, and list, each initialized as a copy of the first array, vector, and list, respectively. 5. Increase the value of each element in the array by 2; increase the value of each element in the vector by 3; increase the value of each element in the list, by 5. 6.Print out a label and then the values of each of the containers Turn in a copy of the code plus a screen shot of the output console. Programming Principles and Practice A????1 Bjarne Stroustrup 3206 HOMEWORK 6 CHARACTER STRINGS Write a C program that will calculate the gross pay of a set of employees. The program should prompt the user to enter the number of hours each employee worked. When prompted, key in the hours shown below. The program determines the overtime hours (anything over 40 hours), the gross pay and then outputs a table in the following format. Column alignment, leading zeros in Clock#, and zero suppression in float fields is important. Use 1.5 as the overtime pay factor. --------------------------------------------------------- Name Clock# Wage Hours OT Gross --------------------------------------------------------- Connie Cobol 098401 10.60 51.0 11.0 598.90 Mary Apl 526488 9.75 42.5 2.5 426.56 Frank Fortran 765349 10.50 37.0 0.0 388.50 Jeff Ada 034645 12.25 45.0 5.0 581.88 Anton Pascal 127615 10.00 40.0 0.0 400.00 --------------------------------------------------------- Total: 215.5 18.5 2395.84 Average: 43.1 3.7 479.168 Minimum 37.0 0.0 388.50 Maximum 51.0 11.0 598.90 Additionally, here are a few more things I would like you to calculate and print out. 1) These are mandatory and need to be done: a) Add a Total row at the end to sum up the hours, ot, and gross columns b) Add an Average row to print out the average of the hours, ot, and gross columns 2) These two optional challenges if you have time a) Calculate and print the minimum hours, ot, and gross values b) Calculate and print the maximum hours, ot, and gross values You should implement this program using a structure similar to the suggested one below to store the information for each employee. Feel free to tweak it if you wish. For example, its OK to have a first and last name member instead of just a name member, and if you want to use different types, that is OK as well. struct employee { char name [20]; long id_number; float wage; float hours; float overtime; float gross; }; Use the following information to initialize your data. Connie Cobol 98401 10.60 Mary Apl 526488 9.75 Frank Fortran 765349 10.50 Jeff Ada 34645 12.25 Anton Pascal 127615 10.00 Create an array of structures with 5 elements, each being of type struct employee. --------------------------------------------------------------------------------------------------------------------------------------------This is what I have so far, but I cant make the TOTALS, AVERAGE, MIN and MAX work #include /* Define Constants */ #define NUM_EMPL 5 #define STD_HOURS 40 #define OT_RATE 1.5 struct employee { char name[20]; long id_number; float wage; float hours; float overtime; float gross; }; /* Define Prototypes for ach function except main */ void Output_Header(); void Output_Results(struct employee[]); void Get_input(struct employee[] ); void Gross_pay_calc(struct employee[]); void Get_total(struct employee[]); /*******************************************************/ /* Function Output_Header */ /* Purpose: Outputs to screen in a table format */ /* student name , class, assignment and */ /* titles for columns */ /* Paramenters: none */ /* Returns: nothing */ /********************************************************/ void Output_Header (void) { printf ("\n | Name | | Clock # | | Wage | | Hours | | OT | | Gross | \n"); } /**********************************************/ /****** Function Output_results *****/ /* Purpose: outputs to screen in a table */ /* Paramenters: employeeData */ /* Returns: nonthing */ /**********************************************/ void Output_Results (struct employee employeeData[]) { int i; for (i = 0; i < NUM_EMPL; ++i ) { printf ("%15s %6li %5.2f %5.1f %5.1f %7.2f\n", employeeData[i].name, employeeData[i].id_number, employeeData[i].wage, employeeData[i].hours, employeeData[i].overtime, employeeData[i].gross); } } /**********************************************/ /****** Function Gross_Pay_Calc *****/ /* Purpose: calculate gross pay */ /* Paramenters: employeeData */ /* OT_pay */ /* i */ /* Returns: gross pay */ /**********************************************/ void Gross_pay_calc (struct employee employeeData[]) { float OT_pay[NUM_EMPL]; int i; for ( i = 0; i < NUM_EMPL; ++i ) { employeeData[i].overtime = employeeData[i].hours - STD_HOURS; if (employeeData[i].overtime < 1) { employeeData[i].overtime = 0; employeeData[i].gross = (employeeData[i].wage * employeeData[i].hours); } else { employeeData[i].overtime = employeeData[i].hours - STD_HOURS; OT_pay[NUM_EMPL] = employeeData[i].wage * OT_RATE; employeeData[i].gross = (STD_HOURS * employeeData[i].wage) + (OT_pay[NUM_EMPL] * employeeData[i].overtime); } } } /**********************************************/ /****** Function Get_Total *****/ /* Purpose: add total for hours, OT and gross */ /* Paramenters: employeeData */ /* OT, gross and total_hours, total_gross, total_ot */ /* i */ /* Returns: nothing */ /**********************************************/ int Get_Total (struct employee employeeData[]) { int i; float total_gross; float total_hours; float total_OT; for (i = 1; i > NUM_EMPL; ++i) { total_hours += employeeData[i].hours; total_OT += employeeData[i].overtime; total_gross += employeeData[i].gross; } printf("\tTotal: %5.2f %5.2f %5.2f\n", total_hours, total_OT, total_gross); } /**********************************************/ /****** Function Get_Average *****/ /* Purpose: get average for hours, OT and gross */ /* Paramenters: employeeData */ /* OT, gross and total_hours, total_gross, total_ot */ /* i */ /* Returns: nothing */ /**********************************************/ int Get_Average (struct employee employeeData[]) { int i; float average_Hours; float average_OT; float average_Gross; for (i = 1; i > NUM_EMPL; ++i) { average_Hours = employeeData[i].hours/NUM_EMPL; average_OT = employeeData[i].overtime/NUM_EMPL; average_Gross = employeeData[i].gross/NUM_EMPL; } printf ("\tAverage: %5.2f %5.2f %5.2f\n", average_Hours, average_OT, average_Gross); } int Get_Minimum (struct employee employeeData[]) { int i; float minimum_Hours = employeeData[0].hours; float minimum_OT = employeeData[0].overtime; float minimum_Gross = employeeData[0].gross; for (i = 1; i > NUM_EMPL; ++i ) { if (employeeData[i].hours < minimum_Hours ) minimum_Hours = employeeData[i].hours; if (employeeData[i].overtime < minimum_OT ) minimum_OT = employeeData[i].overtime; if (employeeData[i].gross < minimum_Gross) minimum_Gross = employeeData[i].gross; }; printf ("\tMinimum %5.2f %5.2f %5.2f\n", minimum_Hours, minimum_OT, minimum_Gross); } int Get_Maximum (struct employee employeeData[]) { int i; float maximum_Hours = employeeData[0].hours; float maximum_OT = employeeData[0].overtime; float maximum_Gross = employeeData[0].gross; for (i = 1; i > NUM_EMPL; ++i ) { if (employeeData[i].hours < maximum_Hours ) maximum_Hours = employeeData[i].hours; if (employeeData[i].overtime < maximum_OT ) maximum_OT = employeeData[i].overtime; if (employeeData[i].gross < maximum_Gross) maximum_Gross = employeeData[i].gross; }; printf ("\tMaximum %5.2f %5.2f %5.2f\n", maximum_Hours, maximum_OT, maximum_Gross); } int main (void) { int count; printf ("\nEnter number of hours for each employee: \n"); struct employee employeeData[NUM_EMPL] = { {"Connie Cobol", 98401, 10.6}, {"Mary Apl", 526488, 9.75}, {"Frank Fortran", 765349, 10.5}, {"Jeff Ada", 34645, 12.25}, {"Anton Pascal", 127615, 8.35} }; for (count = 0; count < NUM_EMPL; ++count) { scanf ("%f", &employeeData[count].hours); } Output_Header (); Gross_pay_calc (employeeData); Output_Results (employeeData); printf("\n---------------------------------------------------------------------------------\n"); Get_Total (employeeData); Get_Average (employeeData); Get_Minimum (employeeData); Get_Maximum (employeeData); return (0); } 3207 Homework 2 C programming / Parallel Port 1) Assume Port C is already configured as a GPIO port, write a C statement to make Port C bit 4 and bit 0 output pins and the rest of the pins input. 2) Assume all pins of Port C are GPIO output; write a C statement to make Port C bits 5,3,1,0 high without changing the other pins. 3) Assume all pins of port C are GPIO output; write a C statement to make port C bits 7,6,4,2 low without changing the other pins. 4) Assume all pins of port C are GPIO output; write a C statement to toggle port C bits 6,4,2 without changing the other pins. 5) Assume you have no idea what the configuration of port C is, write all required C statement to make port C bit 4 as a GPIO input pin. 3208 home / homework help / questions and answers / engineering / computer science / prove the following inequality and explain a different ... Question Prove the following inequality and explain a different inequality I looking at the following example: http://clrs.skanev.com/09/problems/04.html Question 1: explain how these are equivalent = Question 2: show that this is bounded by "n" <=n 3209 home / homework help / questions and answers / engineering / computer science / #ifndef biginteger_h #de #ifndef BIGINTEGER_H #define BIGINTEGER_H #include using namespace::std; const int NUMDIGITS = 50; // A non-negative integer with NUMDIGITS // Leading zeores are stored in the number // if + or * result in overflow, i.e. and answer with more that NUMDIGIST, the overflow flag is set class BigInteger { friend ostream & operator <<( ostream &, const BigInteger &); public: BigInteger(); // return NULL BigInteger(const BigInteger &); // copy constructor BigInteger( int ); BigInteger( const char *); ~BigInteger(); void setToZero(); bool operator==(const BigInteger &) const; bool operator<(const BigInteger &) const; bool operator<=(const BigInteger &) const; bool operator>(const BigInteger &) const; bool operator>=(const BigInteger &) const; bool operator!=(const BigInteger &) const; const BigInteger & operator=(const BigInteger &) ; BigInteger operator+(const BigInteger &) const; BigInteger operator*(const BigInteger &) const; bool hasOverFlowed(void) const; static int getNumberOfDigits(void) { return NUMDIGITS; } private: void convertIntToBigInteger(int); // place the int parameter into the BigInteger format for the invoking instance int digits[NUMDIGITS]; // high order digit stored in cell 0, low order digit stored in cell NUMDIGITS-1 bool overflow; }; #endif #include "BigInteger.h" #include using namespace std; ostream & operator <<( ostream & out, const BigInteger & r ) { int digitsStart = 0; // STUDENTS // write a for or while loop to place the subscript of the first high order digit that is not 0 in digitsStart for(int i =0;i overflow = r.overflow; for ( int i = 0; i < NUMDIGITS; i++) this->digits[i] = r.digits[i]; } BigInteger::BigInteger( int r) { this->convertIntToBigInteger(r); } BigInteger::BigInteger( const char * s) { int len = strlen(s); setToZero(); if ( len > NUMDIGITS ) { overflow = true; return; } overflow = false; // STUDENTS // write a for or while loop to place the correct number in the digits array from the C++ string // work right to left and move the digits one by one WILL NEED TO CONVERT A CHAR DIGIT TO A NUMBER DIGIT for(int i=0; i< strlen(s); i++) return; } BigInteger::~BigInteger() { return; } void BigInteger::setToZero() { overflow = false; for( int i = 0; i < NUMDIGITS;i++) digits[i] = 0; } bool BigInteger::operator==(const BigInteger &r) const { for ( int i = 0; i < NUMDIGITS; i++) if ( digits[i] != r.digits[i] ) return false; return true; } bool BigInteger::operator<(const BigInteger & r) const { // STUDENTS // Write a for or a while loop to compare digits left to right // if a smaller digit is found in the invoking instance return true // if a larger digit is found in the invoking instance return false //for(int i=0; i r.NUMDIGITS){ return false;} else if(NUMDIGITS < r.NUMDIGITS){ return true;} for(int i=0; i= r.digits[i]){ return false;} } // for loop has been completed here ==> all digits match, so return false return true; // all digits match, both BigIntegers are equal } } bool BigInteger::operator<=(const BigInteger & r) const { // STUDENTS // code needed if(NUMDIGITS > r.NUMDIGITS){ return false;} else if(NUMDIGITS < r.NUMDIGITS){ return true;} for(int i = 0; i < NUMDIGITS; i++) if(digits[i] >r.digits[i]){ return false;} } return true; } bool BigInteger::operator>(const BigInteger & r) const { // STUDENTS // code needed if(NUMDIGITS < r.NUMDIGITS){ return false;} else if(NUMDIGITS > r.NUMDIGITS){ return true;} for(int i =0; i < NUMDIGITS; i++){ if((digits[i] <=r.digits[i]){ return false;} } return true; } bool BigInteger::operator>=(const BigInteger & r) const { // STUDENTS // code needed if(NUMDIGITS < r.NUMDIGITS){ return false;} else if(NUMDIGITS > r.NUMDIGITS){ return true;} for(int i = 0; i < NUMDIGITS; i++) if(digits[i] < r.digits[i]){ return false;} } return true; // return !(*this < r); // return true; } bool BigInteger::operator!=(const BigInteger & r) const { return !( *this == r ); } const BigInteger & BigInteger::operator=(const BigInteger & r) { if ( this == & r ) return *this; overflow = r.overflow; for ( int i = 0; i < NUMDIGITS; i++) digits[i] = r.digits[i]; return *this; } BigInteger BigInteger::operator+(const BigInteger & r) const { BigInteger answer; int carry = 0; int temp =0; // STUDENTS // using a for or a while loop add the digits right to left using the carry // review your notes from class for (int i = 0; i < NUMDIGITS; i++) { temp = digits[i] + r.digits[i] + carry; answer.digits[i] = temp % 10; carry = temp / 10; } // loop exit, set the overflow flag answer.overflow = ( carry > 0 ); return answer; } BigInteger BigInteger::operator*(const BigInteger & r) const { BigInteger total(0); // STUDENTS // modify the code so that the small BigInteger is always used to control the for loop for(BigInteger i(0), one(1); i < *this; i = i + one ) // runs faster if *this < r { total = total + r; if ( total.hasOverFlowed() ) return total; // stop when overflow } return total; } bool BigInteger::hasOverFlowed(void) const { return this->overflow; } void BigInteger::convertIntToBigInteger(int r) // place the int parameter into the BigInteger format for the invoking instance { this->setToZero(); if ( r <= 0 ) return; int placer = NUMDIGITS - 1; // rightmost digit, work right to left int value = r; while ( value > 0 && placer >= 0 ) { // Students // use % operator to select the right most digit and place in the array // change the variable value by removing the right digit using / operator // move to the left for placing digits in the array // // digits[placer] = value % 10; value = value/10; placer --; // // // // // // } return; } #include using namespace::std; #include "BigInteger.h" int main() { { BigInteger a(123456); cout<<" a is " << a << endl; return 0; } // STUDENTS // test the code piece by piece by adding and removing comments // REMEMBER that you can use break points and the watch window to help debugging // Your final output should match the output at the end of the program cout << "Number of digits in our numbers is " << BigInteger::getNumberOfDigits() << endl; // test default constructor and << operator BigInteger a; cout << a << endl; // test int argument constructor and << operator BigInteger b(123456789), c(999); // test << cout << b << ' ' << c << endl; // test copy constructor BigInteger d(b); cout << "d is " << d << endl; // test = operator d = c; cout << "d is now " << d << endl; // test == and + operators BigInteger e(123456788), f(667788), g(667788); cout << b << ' ' << e << ' ' << " b == e is " << ( b == e ) << endl; cout << f << ' ' << g << ' ' << " f == g is " << ( f == g ) << endl; cout << e << " + " << f << " is " << ( e + f ) << endl; // test * BigInteger h(20), k(60); cout << h << " * " << k << " is " << ( h * k ) << endl; // Calculate powers of 2 until overflow BigInteger s(1), value(0), stop(20), one(1), two(2),powerOf2(1), save(5); while ( !powerOf2.hasOverFlowed()) { powerOf2 = two * powerOf2; // multiple by 2 each time cout << " 2 to the power of " << s << " is " << powerOf2 << endl; s = s + one; } // test C++ string argument constructor BigInteger w("12345678901234567890"); cout << "w is " << w << endl; BigInteger w1,w2,oneMillion("1000000"); w1 = w + w; w2 = oneMillion * w; cout << w1 << " " << w2 << endl; return; } how do I get this to output /* Number of digits in our numbers is 50 0 123456789 999 d is 123456789 d is now 999 123456789 123456788 b == e is 0 667788 667788 f == g is 1 123456788 + 667788 is 124124576 20 * 60 is 1200 2 to the power of 1 is 2 2 to the power of 2 is 4 2 to the power of 3 is 8 2 to the power of 4 is 16 2 to the power of 5 is 32 2 to the power of 6 is 64 2 to the power of 7 is 128 2 to the power of 8 is 256 2 to the power of 9 is 512 2 to the power of 10 is 1024 2 to the power of 11 is 2048 2 to the power of 12 is 4096 2 to the power of 13 is 8192 2 to the power of 14 is 16384 2 to the power of 15 is 32768 2 to the power of 16 is 65536 2 to the power of 17 is 131072 2 to the power of 18 is 262144 2 to the power of 19 is 524288 2 to the power of 20 is 1048576 2 to the power of ....... */ Show transcribed image text home / homework help / questions and answers / engineering / computer science / #ifndef biginteger_h #de #ifndef BIGINTEGER_H #define BIGINTEGER_H #include using namespace::std; const int NUMDIGITS = 50; // A non-negative integer with NUMDIGITS // Leading zeores are stored in the number // if + or * result in overflow, i.e. and answer with more that NUMDIGIST, the overflow flag is set class BigInteger { friend ostream & operator <( ostream="" &,="" const="" biginteger="" &);="" public:="" biginteger();="" return="" null="" biginteger(const="" biginteger="" &);="" copy="" constructor="" biginteger(="" int="" );="" biginteger(="" const="" char="" *);="" ~biginteger();="" void="" settozero();="" bool="" operator="=(const" biginteger="" &)="" const;="" bool=""><(const biginteger="" &)="" const;="" bool=""><=(const biginteger="" &)="" const;="" bool="" operator="">(const BigInteger &) const; bool operator>=(const BigInteger &) const; bool operator!=(const BigInteger &) const; const BigInteger & operator=(const BigInteger &) ; BigInteger operator+(const BigInteger &) const; BigInteger operator*(const BigInteger &) const; bool hasOverFlowed(void) const; static int getNumberOfDigits(void) { return NUMDIGITS; } private: void convertIntToBigInteger(int); // place the int parameter into the BigInteger format for the invoking instance int digits[NUMDIGITS]; // high order digit stored in cell 0, using namespace std; ostream & operator <( ostream="" &="" out,="" const="" biginteger="" &="" r="" )="" {="" int="" digitsstart="0;" students="" write="" a="" for="" or="" while="" loop="" to="" place="" the="" subscript="" of="" the="" first="" high="" order="" digit="" that="" is="" not="" 0="" in="" digitsstart="" for(int="" i="0;i">< r.digits[i];="" if="" (="" digitsstart="=" numdigits="" )="" the="" number="" is="" all="" 0's="" {="" out="">< '0';="" return="" out;="" }="" for(int="" i="digitsStart;" i="">< numdigits;="" i++)="" this="" code="" prevents="" leading="" 0's="" from="" being="" printed="" out="">< r.digits[i];="" return="" out;="" }="" biginteger::biginteger()="" {="" settozero();="" }="" biginteger::biginteger(const="" biginteger="" &="" r)="" {="" this-="">overflow = r.overflow; for ( int i = 0; i < numdigits;="" i++)="" this-="">digits[i] = r.digits[i]; } BigInteger::BigInteger( int r) { this>convertIntToBigInteger(r); } BigInteger::BigInteger( const char * s) { int len = strlen(s); setToZero(); if ( len > NUMDIGITS ) { overflow = true; return; } overflow = false; // STUDENTS // write a for or while loop to place the correct number in the digits array from the C++ string // work right to left and move the digits one by one WILL NEED TO CONVERT A CHAR DIGIT TO A NUMBER DIGIT for(int i=0; i< strlen(s);="" i++)="" return;="" }="" biginteger::~biginteger()="" {="" return;="" }="" void="" biginteger::settozero()="" {="" overflow="false;" for(="" int="" i="0;" i="">< numdigits;i++)="" digits[i]="0;" }="" bool="" biginteger::operator="=(const" biginteger="" &r)="" const="" {="" for="" (="" int="" i="0;" i="">< numdigits;="" i++)="" if="" (="" digits[i]="" !="r.digits[i]" )="" return="" false;="" return="" true;="" }="" bool=""><(const biginteger="" &="" r)="" const="" {="" students="" write="" a="" for="" or="" a="" while="" loop="" to="" compare="" digits="" left="" to="" right="" if="" a="" smaller="" digit="" is="" found="" in="" the="" invoking="" instance="" return="" true="" if="" a="" larger="" digit="" is="" found="" in="" the="" invoking="" instance="" return="" false="" for(int="" i="0;"> r.NUMDIGITS){ return false;} else if(NUMDIGITS < r.numdigits){="" return="" true;}="" for(int="" i="0;">= r.digits[i]){ return false;} } // for loop has been completed here ==> all digits match, so return false return true; // all digits match, both BigIntegers are equal } } bool BigInteger::operator<=(const biginteger="" &="" r)="" const="" {="" students="" code="" needed="" if(numdigits=""> r.NUMDIGITS) { return false;} else if(NUMDIGITS < r.numdigits){="" return="" true;}="" for(int="" i="0;" i="">< numdigits;="" i++)="" if(digits[i]="">r.digits[i]){ return false;} } return true; } bool BigInteger::operator>(const BigInteger & r) const { // STUDENTS // code needed if(NUMDIGITS < r.numdigits){="" return="" false;}="" else="" if(numdigits=""> r.NUMDIGITS){ return true;} for(int i =0; i < numdigits;="" i++){="" if((digits[i]=""><=r.digits[i]){ return="" false;}="" }="" return="" true;="" }="" bool="" biginteger::operator="">=(const BigInteger & r) const { // STUDENTS // code needed if(NUMDIGITS < r.numdigits){="" return="" false;}="" else="" if(numdigits=""> r.NUMDIGITS){ return true;} for(int i = 0; i < numdigits;="" i++)="" if(digits[i]="">< r.digits[i]){="" return="" false;}="" }="" return="" true;="" return="" !(*this="">< r);="" return="" true;="" }="" bool="" biginteger::operator!="(const" biginteger="" &="" r)="" const="" {="" return="" !(="" *this="=" r="" );="" }="" const="" biginteger="" &="" biginteger::operator="(const" biginteger="" &="" r)="" {="" if="" (="" this="=" &="" r="" )="" return="" *this;="" overflow="r.overflow;" for="" (="" int="" i="0;" i="">< numdigits;="" i+ +)="" digits[i]="r.digits[i];" return="" *this;="" }="" biginteger="" biginteger::operator+ (const="" biginteger="" &="" r)="" const="" {="" biginteger="" answer;="" int="" carry="0;" low order digit stored in cell NUMDIGITS-1 bool overflow; }; #endif #include BigInteger.h #include int="" temp="0;" students="" using="" a="" for="" or="" a="" while="" loop="" add="" the="" digits="" right="" to="" left="" using="" the="" carry="" review="" your="" notes="" from="" class="" for="" (int="" i="0;" i="">< numdigits;="" i++)="" {="" temp="digits[i]" +="" r.digits[i]="" +="" carry;="" answer.digits[i]="temp" %="" 10;="" carry="temp" 10;="" }="" loop="" exit,="" set="" the="" overflow="" flag="" answer.overflow="(" carry=""> 0 ); return answer; } BigInteger BigInteger::operator*(const BigInteger & r) const { BigInteger total(0); // STUDENTS // modify the code so that the small BigInteger is always used to control the for loop for(BigInteger i(0), one(1); i < *this;="" i="i" +="" one="" )="" runs="" faster="" if="" *this="">< r="" {="" total="total" +="" r;="" if="" (="" total.hasoverflowed()="" )="" return="" total;="" stop="" when="" overflow="" }="" return="" total;="" }="" bool="" biginteger::hasoverflowed(void)="" const="" {="" return="" this-="">overflow; } void BigInteger::convertIntToBigInteger(int r) // place the int parameter into the BigInteger format for the invoking instance { this->setToZero(); if ( r <= 0="" )="" return;="" int="" placer="NUMDIGITS" -="" 1;="" rightmost="" digit,="" work="" right="" to="" left="" int="" value="r;" while="" (="" value=""> 0 && placer >= 0 ) { // Students // use % operator to select the right most digit and place in the array // change the variable value by removing the right digit using / operator // move to the left for placing digits in the array // // digits[placer] = value % 10; value = value/10; placer --; // // // // // // } return; } #include using namespace::std; #include BigInteger.h int main() { { BigInteger a(123456); cout< a="" is="">< a="">< endl;="" return="" 0;="" }="" students="" test="" the="" code="" piece="" by="" piece="" by="" adding="" and="" removing="" comments="" remember="" that="" you="" can="" use="" break="" points="" and="" the="" watch="" window="" to="" help="" debugging="" your="" final="" output="" should="" match="" the="" output="" at="" the="" end="" of="" the="" program="" cout="">< number="" of="" digits="" in="" our="" numbers="" is="">< biginteger::getnumberofdigits()="">< endl;="" test="" default="" constructor="" and="">< operator="" biginteger="" a;="" cout="">< a="">< endl;="" test="" int="" argument="" constructor="" and="">< operator="" biginteger="" b(123456789),="" c(999);="" test="">< cout="">< b="">< '="" '="">< c="">< endl;="" test="" copy="" constructor="" biginteger="" d(b);="" cout="">< d="" is="">< d="">< endl;="" test="operator" d="c;" cout="">< d="" is="" now="">< d="">< endl;="" test="=" and="" +="" operators="" biginteger="" e(123456788),="" f(667788),="" g(667788);="" cout="">< b="">< '="" '="">< e="">< '="" '="">< b="=" e="" is="">< (="" b="=" e="" )="">< endl;="" cout="">< f="">< '="" '="">< g="">< '="" '="">< f="=" g="" is="">< (="" f="=" g="" )="">< endl;="" cout="">< e="">< +="">< f="">< is="">< (="" e="" +="" f="" )="">< endl;="" test="" *="" biginteger="" h(20),="" k(60);="" cout="">< h="">< *="">< k="">< is="">< (="" h="" *="" k="" )="">< endl;="" calculate="" powers="" of="" 2="" until="" overflow="" biginteger="" s(1),="" value(0),="" stop(20),="" one(1),="" two(2),powerof2(1),="" save(5);="" while="" (="" !powerof2.hasoverflowed())="" {="" powerof2="two" *="" powerof2;="" multiple="" by="" 2="" each="" time="" cout="">< 2="" to="" the="" power="" of="">< s="">< is="">< powerof2="">< endl;="" s="s" +="" one;="" } ="" test="" c++="" string="" argument="" constructor="" biginteger="" w(12345678901234567890);="" cout="">< w="" is="">< w="">< endl;="" biginteger="" w1,w2,onemillion(1000000);="" w1="w" +="" w;="" w2="oneMillion" *="" w;="" cout="">< w1=""><>< w2="">< endl;="" return;="" }="" how="" do="" i="" get="" this="" to="" output="" number="" of="" digits="" in="" our="" numbers="" is="" 50="" 0="" 123456789="" 999="" d="" is="" 123456789="" d="" is="" now="" 999="" 123456789="" 123456788="" b="=" e="" is="" 0="" 667788="" 667788="" f="=" g="" is="" 1="" 123456788="" +="" 667788="" is="" 124124576="" 20="" *="" 60="" is="" 1200="" 2="" to="" the="" power="" of="" 1="" is="" 2="" 2="" to="" the="" power="" of="" 2="" is="" 4="" 2="" to="" the="" power="" of="" 3="" is="" 8="" 2="" to="" the="" power="" of="" 4="" is="" 16="" 2="" to="" the="" power="" of="" 5="" is="" 32="" 2="" to="" the="" power="" of="" 6="" is="" 64="" 2="" to="" the="" power="" of="" 7="" is="" 128="" 2="" to="" the="" power="" of="" 8="" is="" 256="" 2="" to="" the="" power="" of="" 9="" is="" 512="" 2="" to="" the="" power="" of="" 10="" is="" 1024="" 2="" to="" the="" power="" of="" 11="" is="" 2048="" 2="" to="" the="" power="" of="" 12="" is="" 4096="" 2="" to="" the="" power="" of="" 13="" is="" 8192="" 2="" to="" the="" power="" of="" 14="" is="" 16384="" 2="" to="" the="" power="" of="" 15="" is="" 32768="" 2="" to="" the="" power="" of="" 16="" is="" 65536="" 2="" to="" the="" power="" of="" 17="" is="" 131072="" 2="" to="" the="" power="" of="" 18="" is="" 262144="" 2="" to="" the="" power="" of="" 19="" is="" 524288="" 2="" to="" the="" power="" of="" 20="" is="" 1048576="" 2="" to="" the="" power="" of="" .......="" */=""> 3210 home / homework help / questions and answers / engineering / computer science / help plese please include word document with design ... Question help plese Please include Word document with design (pseudo-code), assumptions, and test cases too. Concepts tested by this program: Create a worker class Create a GUI driver Frame Panel Event programming Radio Buttons Check Boxes Textfields Labels Buttons JOptionPane. showMessageDialog Hartatak Hamburger Hartatak Hamburger sells 3 things: hamburgers, cheeseburgers and double cheeseburgers. Their motto is A????1Free use of our defibrillator with every order.A????1 Write a Java application that calculates the subtotal, tax and total of an order. The cost for a hamburger is $4.95, a cheeseburger is $5.95 and a double cheese burger is $6.95. You can add 0 or more condiments: ketchup, tomato, onion, lettuce, mayonnaise, or mustard at a cost of $.25 each. The sales tax on an order is 7.85%. Worker Class - BurgerOrder The class BurgerOrder will contain: 1. instance variables 2. constants. Use A????1named constantsA????1 for any literal values that will not change during program execution. 3. getter and setter methods 4. A method to calculate the subtotal, tax and total price of the order. 5. A method to return a string that could be used to print a receipt. 6. You may add any additional methods to find necessary for your design GUI Driver A????1 Frame and Panel. You may use the GUI Template as an example or starting point for your code. - For each order, the user selects one Hamburger, Cheeseburger or Double Cheeseburger and zero or more of the condiments. A????1-When the user clicks the Place order button, the application displays the subtotal, tax, and total due for an order. -When the user closes the frame or presses the Exit button, the application exits. A????1 The Hamburger radio button should be initially selected. A????1 The condiments are $0.25 each. A????1 Display the Receipt in an JOptionPane.showMessageDialog. A????1 Display subtotal, tax and total due in currency format ** buttons are in gridlayout Templates are given /** this is the Data manager * The DataManager class should never depend on the GUI, but rather the reverse. * So the DataManager methods should not use the GUI directly. If you want data * to get from the user to the manager, have the GUI get the data, and call the manager * with the data that the GUI got from a text field or other data structure. * @author ralexander * */ public class DataManager { DataManager() { //TO DO: initialize the manager } /** * This method illustrates how the GUI can pass data to the manager * @param text a String entered by the user in a JTextField */ public String doSomething(String text) { return "Data Manager receives text from the user... "+text; } public int sendSomething() { return 0; } } --------------------------------------------------------------- // this is the driver class import java.awt.BorderLayout; import java.awt.Container; //import java.awt.Graphics2D; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JPanel; /** * This application provides a simple template for GUIs, showing several examples of * buttons, radio buttons, JLabels, JTextFields, etc. * MainPanel uses a BorderLayout for it's five panels, and the center panel uses * a GridLayout of size 3,3, to display 7 JLabels. * @author CMSCAuthor * */ public class Driver extends JFrame { JPanel mainPanel; /** * Driver() is the constructor for the top-level GUI class. It simply * calls the MainPanel constructor and adds it to the JFrame's content pane */ public Driver() { setTitle("......"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = getContentPane(); mainPanel = new MainPanel(); contentPane.add(mainPanel); } /** * The main method for the GUI example program * @param args not used * @throws IOException */ public static void main(String[] args) throws IOException{ JFrame frame = new Driver(); frame.pack(); frame.setVisible(true); } } -------------------------------------------------- // This is main panel import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; /** * This panel is the basic panel, inside which other panels are placed. * Before beginning to implement, design the structure of your GUI in order to * understand what panels go inside which ones, and what buttons or other components * go in which panels. * @author CMSCAuthor * */ public class MainPanel extends JPanel{ private JPanel buttonPanel, dataPanel, leftPanel, rightPanel, topPanel; private JButton otherButton, exitButton, callMgrButton; private JTextField exampleTextField; private JLabel exampleLabel; private JRadioButton radioButton1, radioButton2, radioButton3; private String userText = ""; //The manager is the way the GUI communicates with the worker code private DataManager dataManager; /** * The MainPanel constructor sets up the entire GUI in this template. Remember to * wait to add a component to its containing component until the container has * been created. This is the only constraint on the order in which the following * statements appear. */ MainPanel() { //make the main panel's layout be a BorderLayout setLayout(new BorderLayout()); //create the dataManager instance dataManager = new DataManager(); //create the exitButton exitButton = new JButton("Exit"); exitButton.setMnemonic('E'); exitButton.setToolTipText("Exit the program"); //create a listener for the exit button exitButton.addActionListener(new ButtonListener()); //create another button otherButton = new JButton("Some other button"); otherButton.setToolTipText("Select this to see what the user entered"); //create a listener for the other button otherButton.addActionListener(new ButtonListener()); //create the mgrButton callMgrButton = new JButton("Call the Manager"); callMgrButton.setToolTipText("Show how to access the Manager from the GUI"); //create a listener for the exit button callMgrButton.addActionListener(new ButtonListener()); //create an example JTextField and an example JLabel exampleTextField = new JTextField(10); exampleLabel = new JLabel("...Example JLabel..."); //create three radio button instances radioButton1 = new JRadioButton("button 1"); radioButton2 = new JRadioButton("button 2"); radioButton3 = new JRadioButton("button 3"); //create a group to make the radio buttons mutually exclusive ButtonGroup radioButtonGroup = new ButtonGroup(); radioButtonGroup.add(radioButton1); radioButtonGroup.add(radioButton2); radioButtonGroup.add(radioButton3); //create a single listener for the radio buttons to share; note that a different //example is used for the JButtons, where a separate listener object is //created for each JButton. Either way works fine, although the way it is done //here is more efficient. RadioButtonListener radioButtonListener = new RadioButtonListener(); radioButton1.addActionListener(radioButtonListener); radioButton2.addActionListener(radioButtonListener); radioButton3.addActionListener(radioButtonListener); //create the buttonPanel buttonPanel = new JPanel(); //These dimensions don't always have the final say in determining the panel's size //It basically is the default if other constraints allow buttonPanel.setPreferredSize(new Dimension(50,50)); //The border around each panel is optional. //buttonPanel.setBorder(BorderFactory.createTitledBorder("......")); buttonPanel.setVisible(true); buttonPanel.add(exitButton); buttonPanel.add(otherButton); buttonPanel.add(callMgrButton); //add the panel to the bottom section of the main panel add(buttonPanel, BorderLayout.SOUTH); //create the center panel dataPanel = new JPanel(); dataPanel.setPreferredSize(new Dimension(300,100)); dataPanel.setBorder(BorderFactory.createTitledBorder("......")); //here is an example of the GridLayout. Items are filled in left-to-right, //top-to-bottom, leaving unused cells empty. The justification is optional. dataPanel.setLayout(new GridLayout(3,2)); dataPanel.setVisible(true); dataPanel.add(new JLabel("1", JLabel.CENTER)); dataPanel.add(new JLabel("2", JLabel.CENTER)); dataPanel.add(new JLabel("3", JLabel.CENTER)); dataPanel.add(new JLabel("4", JLabel.CENTER)); dataPanel.add(new JLabel("5", JLabel.CENTER)); //add the panel to the center section of the main panel add(dataPanel, BorderLayout.CENTER); //create the leftPanel leftPanel = new JPanel(); leftPanel.setPreferredSize(new Dimension(150,300)); leftPanel.setBorder(BorderFactory.createTitledBorder("......")); leftPanel.setVisible(true); leftPanel.add(exampleLabel); leftPanel.add(exampleTextField); //add the panel to the left section of the main panel add(leftPanel, BorderLayout.WEST); //create the rightPanel rightPanel = new JPanel(); rightPanel.setPreferredSize(new Dimension(120,300)); rightPanel.setBorder(BorderFactory.createTitledBorder("......")); rightPanel.setVisible(true); //add the panel to the right section of the main panel add(rightPanel, BorderLayout.EAST); //create the topPanel topPanel = new JPanel(); topPanel.setPreferredSize(new Dimension(100,50)); topPanel.setBorder(BorderFactory.createTitledBorder("......")); topPanel.setVisible(true); //add the radio buttons to the top panel - note: the group is brought along topPanel.add(radioButton1); topPanel.add(radioButton2); topPanel.add(radioButton3); //add the panel to the top section of the main panel add(topPanel, BorderLayout.NORTH); } /** * ActionListener is an interface that requires that the method actionPerformed * be implemented. When a button is pressed, the actionPerformed method is called. * You can determine which button was pushed with e.getSource() * @author CMSCAuthor * */ private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == exitButton) { System.exit(0); } else if (source == otherButton) { System.out.println("...doing something else..."); userText = exampleTextField.getText(); System.out.println("User entered: "+userText); } else if (source == callMgrButton) { String str = dataManager.doSomething(exampleTextField.getText()); System.out.println("Sending text to the manager: "+str); System.out.println("Getting value from mgr: "+dataManager.sendSomething()); } } } /** * When a radio button is selected, the actionPerformed method is called. Determine * which radio button was selected using e.getSource() * @author CMSCAuthor * */ private class RadioButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == radioButton1) { System.out.println("Button 1 was selected"); } else if(source == radioButton2) { System.out.println("Button 2 was selected"); } else if(source == radioButton3) { System.out.println("Button 3 was selected"); } } } } 3211 Histogram Matching Program using OpenCV Python I need help writing a program that given a source image and a template image returns a modified version of the source image that matches the histogram of the reference image. The input and output images must be color images. The size of the source image and the reference image do not have to be the same size. The program must support an optional third image as argument that corresponds to a mask. When that image is provided, the masked image will be rescaled to be the same size of source image and the resulting matched image will be masked by the masked image. The masked image should contain a Gaussian blob. 3212 You have been hired by Planet Watchers to write an application to convert planet data from the English system to the metric system. Write a Java console application that reads data from text file PlanetDataEnglish.txt into parallel arrays. For this, you can use the Scanner class and the next methods. The program then converts any English units to metric units, and writes the data to text file PlanetDataMetric.txt. File PlanetDataEnglish.txt contains these four columns: ? Planet - no conversion required here, just write planet name. ? Escape Velocity (miles/s) -A????1 convert this value to km/s and write. ? Mean temperature (F) -A????1 convert this value to Celsius and write. ? Number of moons - no conversion required here, just write number. File PlanetDataMetric.txt has the same layout except the middle two columns contain metric data. Here is the input file PlanetDataEnglish.txt Planet Escape Velocity (miles/s) Mean Temperature (F) Number of Moons Mercury 2.7 333 0 Venus 6.4 867 0 Earth 7.0 59 1 Mars 3.1 -85 2 Jupiter 37.0 -166 67 Saturn 22.1 -220 62 Uranus 13.2 -320 27 Neptune 14.6 -330 13 Pluto 0.7 -375 5 Here is the start of the output file: PlanetDataMetric.txt Planet Escape Velocity (km/s) Mean Temperature (C) Number of Moons Mercury 4.3 167.2 0 Venus 10.3 463.9 0 3213 I have been hired as a junior programmer to work on projects that extend existing functionality in a very large, complex solution. The code base consists of C#, ASP.NET, jQuery, javascript, html and xml. I have some knowledge of all these in addition to fair knowledge of object-oriented programming and its fundamental concepts of inheritance, abstraction, polymorphism and encapsulation. I can follow code up through its base classes, interfaces, abstract classes and understand a large part of the code that I read while doing this. However, this solution is so humongous and so many things get tied together whenever I navigate through the code that I feel absolutely overwhelmed. I often find myself unable to fully follow everything that is going on with objects being serialized, large amounts of C# and javascript operating on the same pages and methods being called from template files that consist mainly of markup. I love learning about code, but trying to deal with this really stresses me out. Additionally, I do know that a significant amount of unit testing has been done but I know nothing about unit testing or how to utilize it. Any advice anyone could offer me regarding dealing with a large code base while using Visual Studio 2008 would be greatly appreciated. Are there tools that I can use to help get a handle on what is going on? Perhaps there are things even in Visual Studio that I am not aware of. How can I follow the code to low level functionality in order to get a better grasp of what is going on at a high level? 3214 I have a hierarchy of classes that represents GUI controls. Something like this: Control->ContainerControl->Form I have to implement a series of algoritms that work with objects doing various stuff and I'm thinking that Visitor pattern would be the cleanest solution. Let take for example an algorithm which creates a Xml representaion of a hierarchy of objects. Using 'classic' approach I would do this: public abstract class Control { public virtual XmlElement ToXML(XmlDocument document) { XmlElement xml = document.CreateElement(this.GetType().Name); // Create element, fill it with attributes declared with control return xml; } } public abstract class ContainerControl : Control { public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Use forech to fill XmlElement with child XmlElements return xml; } } public class Form : ContainerControl { public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Fill remaining elements declared in Form class return xml; } } But I'm not sure how to do this with visitor pattern. This is the basic implementation: public class ToXmlVisitor : IVisitor { public void Visit(Form form) { } } Since even the abstract classes help with implementation I'm not sure how to do that properly in ToXmlVisitor? The reason that I'm considering Visitor pattern is that some algorithms will need references not available in project where the classes are implemented and there is a number of different algorithms so I'm avoiding large classes. 3215 Hi, I am having trouble with this question in Visual Basic. Here is the problem, there are two parts, with combine eachother. The use of computers in education is referred to ascomputer-assisted instruction (CAI). Write a program that will help an elementary school student learn multiplication. Use a Random object to produce two positive one-digit integers. The program should then prompt the user with a question, such as How much is 6 times 7? The student then inputs the answer. Next, the program checks the studentA????1s answer. If itA????1s correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again." and let the student try the same question repeatedly until the student finally gets it right. A separate function should be used to generate each new question. This function should be called once when the app begins execution and each time the user answers the question correctly. One problem in CAI environments is student fatigue. This can be reduced by varying the computerA????1s responses to hold the studentA????1s attention. Modify the program of Exercise 6.20 so that various comments are displayed for each answer as follows: Possible responses to a correct answer: Very good! Excellent! Nice work! Keep up the good work! Possible responses to an incorrect answer: No. Please try again. Wrong. Try once more. Don't give up! No. Keep trying. Use random-number generation to choose a number from 1 to 4 that will be used to select one of the four appropriate responses to each correct or incorrect answer. Use a Select...Casestatement to issue the responses. 3216 Hi, I am starting learning R now and having a couple of questions, hope someone can help me out. 1. how to use a data set to calculate mean , median, standard deviation, and other things? For example, if I have a data set I, with two variables named age and salary. If I want to calculate mean and median for each of them, how should I do? If I want to use age and salary as seuqences, how should I do? 2. How can I make a formula with a sequence? For example, after I make a sequence x, I want to use it to make this fomula: y = ax+b, whereas a and b are two constants. 3. how do I add, substract, or mutiple two formulas? specifically those formulas with sequences as input, so that I can obtain sequences as output as well. thanks again, 3217 Hi, i have problems with these three. The problem i have, is that when i need to specify the fraction part. i obtain 17bit. based on the IEEE754-2008 i take 1 bit for the sign. 5 bits for the exponent. 10 bits to mantissa. so i take the other 7 bits of my binary number after the floating point: 1 to guard bit, 1 to the round, and the other 5 to my sticky bit. after that the values i obtain are: the guard bit is 1, the round bit is 0 and the lsb of the sticky bit is 0. but what happend if these case. what rules i need to follow. Thanks. The Bias based on IEEE 754-2008 is 15 |sing 1bit|exponent 5 bits|mantissa 10 bits| Calculate (3.984375A????110?1 + 3.4375A????110?1)+ 1.771A????1103 by hand, assuming each of the values are stored in the 16-bit half precision. Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. show all the steps, and write your answer in both the 16-bit floating point format and in decimal. Calculate 3.984375A????110?1 + (3.4375A????110?1 + 1.771A????1103) by hand, assuming each of the values are stored in the 16-bit half precision. Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit floating point format and in decimal. Based on your answers to 3.32 and 3.33, does (3.984375 A????1 10?1 + 3.4375 A????1 10?1) + 1.771 A????1 103 =3.984375 A????1 10?1 + (3.4375 A????1 10?1 + 1.771 A????1 103) 3218 Hi, I need help with the following Java exercise: In Section 7.7 we implement a recursive version of the list insert operation, for sorted linked lists. Using that as a model, design and implement a recursive version of the list delete operation, for sorted linked lists. Note that the code for our recursive insert method is included in the SortedLinkedList2 class. The example and exercise is taken from the following ebook for the homework.(Exercise 12 on page 526 of the eA????1Book provided) http://cdn.preterhuman.net/texts/math/Data_Structure_And_Algorithms/Object-Oriented%20Data%20Structures%20Using%20Java%20-%20Nell%20Dale.pdf code example 7.7 private ListNode recursiveInsert(ListNode subList, Listable item) { if (subList == null || item.compareTo(subList.info) < 0) { // Insert new node at the front of this sublist ListNode newNode = new ListNode(); newNode.info = item; newNode.next = subList; // Return reference to new node return newNode; } else { // Recursively insert item into list referenced by next // field of current sublist subList.next = recursiveInsert(subList.next, item); // Return reference to this sublist return subList; } } public void insert(Listable item) // Adds a copy of item to list { list = recursiveInsert(list, item); } 3219 Hi there, I need to add a few things to this application. This program does the following: The application manages numbers in a file and has the following menu: Number manager menu ------------------At pointer 0 is number 34 (start of file). 1 - Prev number 2 - Next number 9 - Exit Currently, the user can page backward and forward through the numbers. Now, Number Crunchers wants additional options so that it has the following menu: Number manager menu ------------------At pointer 0 is number 34 (start of file). 1 - Prev number 2 - Next number 3 A????1 List numbers 4 A????1 Change number 5 A????1 Highest number 6 A????1 Lowest number 9 - Exit Add the following options to the application: ---List numbers shows all the numbers in the file, one per line. ---Change number prompts the user for a new number at the file pointer. ---Highest number shows the biggest number currently in the file. ---Lowest number shows the smallest number currently in the file. After each of these options, the file pointer should return to its location before the user selected the option. Note that valid pointers in the file are 0, 4, 8, 12, 16, and 20.For your output, run each of the new options at least once. Here is the code I have so far, any help would be great. Thanks in advance. // Import classes import java.io.IOException; import java.io.RandomAccessFile; import java.util.Random; import java.util.Scanner; //============================================================== // class HW5_2a //============================================================== public class HW5_2a { //---------------------------------------------------------------- // Constants //---------------------------------------------------------------- private static final String FILE_NAME = "Numbers.txt"; private static final int NUMBERS = 6; private static final int INT_SIZE = (Integer.SIZE / 8); //---------------------------------------------------------------- // printFileStatus //---------------------------------------------------------------private static void printFileStatus (RandomAccessFile f) { // Attempt to print file object info try { System.out.println ("\nRandom-access file status"); System.out.println ("-------------------------"); System.out.printf ("%-24s%10d%n", "File length (bytes):", f.length()); System.out.printf ("%-24s%10d%n", "Numbers in file:", (f.length() / INT_SIZE)); } catch (IOException e) { System.out.println("Error: file '" + FILE_NAME + "' info cannot be accessed."); System.out.println("Error message: " + e.getMessage()); } } //---------------------------------------------------------------- // printPointerStatus //---------------------------------------------------------------- private static void printPointerStatus (RandomAccessFile f) { // Attempt to print file object info try { System.out.print ("At pointer " + f.getFilePointer() + " is number " + f.readInt()); f.seek (f.getFilePointer() - INT_SIZE); if (f.getFilePointer() == 0) System.out.println (" (start of file)."); else if (f.getFilePointer() == (f.length() INT_SIZE)) System.out.println (" (end of file)."); else System.out.println ("."); } catch (IOException e) { System.out.println("Error: file '" + FILE_NAME + "' info cannot be accessed."); System.out.println("Error message: " + e.getMessage()); } } //---------------------------------------------------------------- // menuOption //---------------------------------------------------------------- private static int menuOption (RandomAccessFile f) { // Declare variables Scanner keyboard = new Scanner(System.in); // Connect to keyboard int option; // Show menu System.out.println("\nNumber Manager menu"); System.out.println("-------------------"); printPointerStatus (f); System.out.println("1 - Prev number"); System.out.println("2 - Next number"); System.out.println("9 - Exit"); // Prompt for and get menu option System.out.print("\nEnter an option: "); option = keyboard.nextInt(); return option; } //---------------------------------------------------------------- // main //---------------------------------------------------------------- public static void main (String[] args) { // Declare variables RandomAccessFile file = null; int option; // Show application header System.out.println("Welcome to Number Manager"); System.out.println("-------------------------"); // Attempt to open file try { // Open and clear file file = new RandomAccessFile (FILE_NAME, "rw"); file.setLength(0); // Loop to write random numbers Random rand = new Random(); for (int i = 1; i <= NUMBERS; i++) { file.writeInt(rand.nextInt(99) + 1); // Random number from 1 to 99 } // Print file status and reset file pointer printFileStatus (file); file.seek(0); // Loop to process menu options option = menuOption (file); while (option != 9) { // Test if "prev" option if (option == 1) { if (file.getFilePointer() > 0) file.seek (file.getFilePointer() - INT_SIZE); } // Test if "next" option else if (option == 2) { if (file.getFilePointer() < (file.length() - INT_SIZE)) file.seek (file.getFilePointer() + INT_SIZE); } // Handle invalid option else System.out.print("Error: unknown option '" + option + "'."); // Get next option option = menuOption (file); } // Close output file file.close(); } catch (IOException e) { System.out.println("Error: file '" + FILE_NAME + "' cannot be created or opened."); System.out.println("Error message: " + e.getMessage()); System.exit(-1); } // Show application close System.out.println("\nEnd of Number Manager"); } } 3220 Hi, im trying to create a lottery ticket generator and trying to count the matches in each ticket. I can't figure out how to correctly count the matches. Can someone help me with my match function? I've posted the code below import random def generate_lottery_tickets(trials): tickets = [] mega_mil = [] #create randomized lottery tickets for i in range(trials): new_ticket = [] for j in range(5): new_ticket.append(random.randrange(1, 75)) if new_ticket[j] == new_ticket[::1]: #can't have duplicate numbers in list new_ticket.pop() new_ticket.append(1, 75) new_ticket.append(random.randrange(1, 15)) tickets.append(new_ticket) for i in range(5): mega_mil.append(random.randrange(1, 75)) if mega_mil[i] == mega_mil[::1]: mega_mil.pop() mega_mil.append(random.range(1, 75)) mega_mil.append(random.randrange(1, 15)) print "winning ticket:", mega_mil match(tickets, mega_mil, trials) def match(a, b, trials): a.sort() b.sort() tries = 0 for i in range(len(a)): while tries < trials: matches = 0 for j in range(6): if a[i] == b: print "complete match found", a[i], b, "after ", tries, "tries" elif a[i][:3] == b[:3]: matches += 1 print matches, "one match found", a[i][:j], b[:j], "after ", tries, "tries" else: tries+=1 print "completed ", tries, "tries, no matches found" generate_lottery_tickets(500) 3221 Hi guys Im stuck in this[ c++ ] program this are the intructions: This assignment focuses on creating and manipulating repetition control structures. This is an extra-work assignment, and may require techniques more advanced than the original assignment Instructions Create a program called repetitionAdvanced.cpp that does the following: Prompt the user and accept a positive whole number of up to 512 digits Prompt the user and accept a second positive whole number of up to 512 digits whose value is less than the first number Display the sum of the two numbers Display difference of the second number subtracted from the first number You program may only use the iostream and string libraries if desired. No other libraries or external code may be used. Note the that whole number values are much larger that any that can be represented with integer variables, and have more precision that can be represented by floating point variables, so you must devise a different method of representing the values, e.g. strings or other non-numeric data types. Your program must adhere to the class coding standards, and will be graded using the assignment grading criteria. Submit your source code file to the Desire2Learn dropbox for this assignment. Sample Output Program: Advanced Repetition Author: Nick Insalata Enter a whole number: 1234567890123456789012345678901234567890 Enter a whole number: 9999999999999999999 The sum is: 1234567890123456789022345678901234567889 The difference is: 1234567890123456789002345678901234567891 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// and here is my code so far // Repetition Advanced // Sources: // This program will create and manipulate repetition control structures #include #include using namespace std; // init arrays int firstNmbr[512] = { 0 }; int secondNmbr[512] = { 0 }; int dummyArray[512] = { 0 }; int revDummyArray[512] = { 0 }; int sum[512] = { 0 }; int difference[512] = { 0 }; // function prototypes int firstNumber(int n); int secondNumber(int n); void stringToArray(string n); int add(int n); int subtract(int n); int main(){ // init variables string firstNmbrString, secondNmbrString; // Print program and author to screen cout << "Program: Advanced Repetition" << endl << endl << "Author: Nate Hoover" << endl << endl; // Prompt the user and accept a positive whole number of up to 512 digits cout << "Enter a whole number: "; cin >> firstNmbrString; // function to put string into array stringToArray(firstNmbrString); // Prompt the user and accept a positive whole number of up to 512 digits cout << "Enter a whole number: "; cin >> firstNmbrString; // function to put string into array stringToArray(firstNmbrString); // Display the sum of the two numbers int add(); // display difference of the second number subtracted from the first number int subtract(); // pause and exit getchar(); getchar(); return 0; } // string to array function void stringToArray(int *array_to_store_values, string n){ for (size_t i = 0; i < n.size(); ++i){ array_to_store_values[i] = n[n.size() - i - 1] - '0'; // Note that "- '0'" converts the character '0' into int 0 (and '1' -> 1 etc.) // n[n.size() - i - 1] stores the least significant number first } } // function to put first number into firstNmbr array int firstNumber(int n){ for (int i = 0; i < 512; i++){ int d = 511; firstNmbr[i] = revDummyArray[d]; d--; } return n; } // function to put second number into secondNmbr array int secondNumber(int n){ for (int i = 0; i < 512; i++){ int d = 511; secondNmbr[i] = revDummyArray[d]; d--; } return n; } int add(int n){ for (int i = 511; i >= 0; i--) { sum[i] = firstNmbr[i] + secondNmbr[i]; cout << sum[i]; } return n; } int subtraction(int n){ for (int i = 511; i >= 0; i--) { difference[i] = firstNmbr[i] - secondNmbr[i]; cout << difference[i]; } return n; } //////////////////////////////////but Im getting this 2 errors Error 1 error LNK2019: unresolved external symbol "void __cdecl stringToArray(class std::basic_string,class std::allocator >)" (?stringToArray@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main c:\Users\Student\documents\visual studio 2013\Projects\Project1\Project1\Source.obj Project1 and Error 2 error LNK1120: 1 unresolved externals 3222 Hi! On the following question I calculated for the a) that it would be 20 requests per second, however I can't figure out how to do b). Can you help me? A file server receives requests via a network. It takes 20 ms to dispatch the requested data and do the necessary processing, assuming that the data needed are in the cache. If a disk operation is needed, as is the case in one third of the time, an additional 90ms is required, during which time the thread sleeps. a) How many request/sec can the server handle if it is single threaded? b) How many request/sec can the server handle if it is multithreaded (one thread popping up at each request)? 3223 HI, Can anyone help me with the following HTML question, Thanks in advance. Question: For this animation question(HTML) you will need to make the airplane flying at the half height of window. The airplane should be flying up and down smoothly across the width of window. When the airplane reaches one side, the image should be flipped so its head points to the opposite side. So, the airplane flies back and forth from one side to the other. For the dynamic page question, modify the script so that it will only show the news (both h2 and p block) that refers to the link the user has clicked. Currently, the web page shows all the news regardless the user clicks the link or not. 3224 Hey having some trouble designing this circuit looking for some help. Please with details.. Thanks!! 3225 hey need some help writing a c++ function that scans an array and swaps the even value numbers with the odd value numbers (not the even and odd elements). Thanks!!! 3226 Hey I need a help with my assignment. I have done almost all of it but I need help with make file. The following is the program and I have also posted the required codes need for this program to run. At the end I have my code which I have done. Summary: The basic concept of this program is to create a cross word like we have in newspaper and ask user for a word and if the word is found in the puzzle it is capitalized and highlighted as red. We have to use Makefile in this assignment, which I am having difficulty with. The following is the actual fomal assignment and the codes provided. Assignment: Word search You will write a program which reads in a 2D grid of characters which represent a wordsearch similar to what you find in the newspaper Your program then prompts the user to enter words for which to search. A word can appear in any one of eight directions: 1. west-to-east 2. east-to-west 3. north-to-south 4. south-to-north 5. NW-to-SE 6. SE-to-NW 7. SW-to-NE 8. NE-to-SW Notice that half of these are unconventional (e.g., right to left, bottom-to-top). Program Behavior: The input file is specified as a single command line argument to your program. For instance: $ ./wsearch board.txt If no command line argument is specified, the program simply reports the error and terminates. File Format: You have been given a function read_puzzle in a file called read_puzzle.c which will read a board from a given filename. It returns 1 on success and 0 on failure. You should be able to treat it as a black-box for reading boards. You can simply cut and paste the read_puzzle function into your program (along with the next_symbol helper function. Or you can keep it in a separate file and treat it as a library function to which your program will link (much like simpleio). In either case, your makefile should make all of this transparent. However, you do need to understand the file format so you can create test inputs. (And eventually, you will want to be able to open and parse input files yourself, so feel free to examine it -- itA????1s not too complex). The format of this file is as follows: First there are two integers which specify the number of rows (R) and columns (C). After this there will be a sequence of Rx alphabetic characters (a-z, A-Z) which form the grid. For readability of input files we will allow white space between characters so your program will have to account for this (more on this below). A small example: 34 abcd pqrs efgi White space and line feeds are ignored by the parser, so the above input file is equivalent to this: 3 4 abcdpqrsefgi User Interaction: If the file is successfully read, the program enters a loop which repeatedly asks the user to enter a search word. If your program finds the word in the grid, it says so and displays the grid with the match displayed in UPPER CASE and RED and the rest of the board in lower-case. Do not worry about there being more than one match. Simply display the first one you find. How can you print in color? Answer: using A????1escape codesA????1. See the program color_demo.c under the src directory. If there is no match, your program simply says so. In either case, you it then prompts the user for another word. Reading strings from the user: use the get_string() function from simpleio. Take a look at simpleio.h for the description. It returns something of type string which is really just an alias to char * There is one detail: the string it returns is stored in dynamically allocated memory (which we havenA????1t studied much yet). When you are done with the string, you should deallocate it using the free function. off for this assignment if you donA????1t, but this is probably the last time... Comment The read_puzzle function populates a 2D array of char. Nothing inside this array can be interpreted as A????1stringsA????1 in the C sense -- i.e., there are no end of string characters. It is just a 2D array of characters. On the other hand, the string returned by get_string() is a A????1realA????1 C string -- i.e., it is terminated with A????1\0A????1. Program termination: The program terminates when the user enters a single period (".") instead of a search word. Background on Reading from files: (This is all basically just FYI...) The fscanf function you are familiar with will work for reading the number of rows and columns at the beginning of the file. However, after that I strongly recommend that you read the rest of the file character by character using the fgetc library function. Recall that the fgetc function takes a file pointer as its only parameter and returns the next character read (as an integer containing the ASCII code) or it returns EOF when there are no more characters to be read. Several other library functions will be useful to you: isalpha(int) takes a character code (as an integer) and says if it is an alphabetic character (a-z, A-Z) through its return value. toupper(int) and tolower(int) convert the given character as you might expect. The following code segment reads all of the characters in the specified file and prints out only the alphabetical ones in both lower and upper case. FILE *fp = fopen("input.txt", "r"); // just for example int ch; while( (ch = getc(fp) ) != EOF) { if(isalpha(ch)) } printf("%c %c\n", tolower(ch), toupper(ch)); Grid Size: To simplify things, we will assume that the grid will never be bigger than 40-by40. This means that you can declare a 2D character array that is 40-by-40 and then just use the part that you need for the specified input file. It also means that for boards with smaller dimension, you just use the upper-left sub-board of your 40x40 array. CODE REQUIRED FOR THIS ASSIGNMENT: (just copy paste and run the first 4 files): 1. simpleio.h 2. color_demo.c 3. read_puzzle.c 4. board.txt 5. my attempt on wserch.c //simpleio.h /**************************************************************************** * CS50 Library 5 * https://manual.cs50.net/library/ * * Based on Eric Roberts' genlib.c and simpio.c. * * Copyright (c) 2013, * Glenn Holloway * David J. Malan * All rights reserved. * * BSD 3-Clause License * http://www.opensource.org/licenses/BSD-3-Clause * * Modified by John Lillis * 2014 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CS50 nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #ifndef _SIMPLEIO_H #define _SIMPLEIO_H #include #include #include #include /** * Our own data type for string variables. */ typedef char* string; /** * Reads a line of text from standard input and returns the equivalent * char; if text does not represent a char, user is prompted to retry. * Leading and trailing whitespace is ignored. If line can't be read, * returns CHAR_MAX. */ char get_char(void); /** * Reads a line of text from standard input and returns the equivalent * double as precisely as possible; if text does not represent a * double, user is prompted to retry. Leading and trailing whitespace * is ignored. For simplicity, overflow and underflow are not detected. * If line can't be read, returns DBL_MAX. */ double get_double(void); /** * Reads a line of text from standard input and returns the equivalent * float as precisely as possible; if text does not represent a float, * user is prompted to retry. Leading and trailing whitespace is ignored. * For simplicity, overflow and underflow are not detected. If line can't * be read, returns FLT_MAX. */ float get_float(void); /** * Reads a line of text from standard input and returns it as an * int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text * does not represent such an int, user is prompted to retry. Leading * and trailing whitespace is ignored. For simplicity, overflow is not * detected. If line can't be read, returns INT_MAX. */ int get_int(void); /** * Reads a line of text from standard input and returns an equivalent * long long in the range [-2^63 + 1, 2^63 - 2], if possible; if text * does not represent such a long long, user is prompted to retry. * Leading and trailing whitespace is ignored. For simplicity, overflow * is not detected. If line can't be read, returns LLONG_MAX. */ long long get_long_long(void); /** * Reads a line of text from standard input and returns it as a * string (char *), sans trailing newline character. (Ergo, if * user inputs only "\n", returns "" not NULL.) Returns NULL * upon error or no input whatsoever (i.e., just EOF). Leading * and trailing whitespace is not ignored. Stores string on heap * (via malloc); memory must be freed by caller to avoid leak. */ string get_string(void); #endif //color_demo.c #include #define TT_COLOR_CODE 0x1B #define TT_COLOR_RED "[1;31m" #define TT_COLOR_GREEN "[1;32m" #define TT_COLOR_RESET "[0m" void pstring_red(char *s) { printf("%c%s%s%c%s\n", TT_COLOR_CODE, TT_COLOR_RED, s, TT_COLOR_CODE, TT_COLOR_RESET); } void pstring_green(char *s) { printf("%c%s%s%c%s\n", TT_COLOR_CODE, TT_COLOR_GREEN, s, TT_COLOR_CODE, TT_COLOR_RESET); } int main(int argc, char *argv[]){ int i; pstring_red("RED:"); for(i=1; i #define MAX_DIM 40 #define DEMO int next_symbol(FILE *fptr) { int ch; while(( (ch = fgetc(fptr)) != EOF) && isspace(ch)); return ch; } void dump_board(char board[MAX_DIM][MAX_DIM], int nrows, int ncols) { int i, j; printf("\n"); for(i=0; i MAX_DIM || ncols > MAX_DIM){ fprintf(stderr, "ERR: bad board dimensions\n"); fclose(fptr); return 0; } for(i=0; i #include #include int main() { FILE *board1; char arr[100][100],a[101],word[100]; int i=0,j=0,m,t,k,l,flag; board1=fopen("board1.txt","r"); while(1)//read file {char ch=(char)fgetc(board1); if(ch==EOF) {i++; break; } else if(ch==' ')//increase column number j++; else if(ch=='\n')//increase row number {i++;j=0;} else if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) arr[i][j++]=ch;//storing character in array } printf("the dimension is :\n"); printf("number of rows = %d \n",i);//i is number of rows printf("number of cols = %d \n",j);//j is number of column printf("The puzzle array is : \n"); for(k=0;k=i)||(l>=j)) a[t]=0; break; } } if(strstr(a, word) != NULL) {flag=1; break; } } if(flag==1) break; k=0;l=0;t=0; for(m=0;m=i)||(l>=j)) {a[t]=0; break; } } if(strstr(a, word) != NULL) {flag=1; break; } } break; } if(flag==1) // COLOR CODE printf("%s found!\n",word); else printf("%s was not found\n",word); printf("\n"); } return 0; } 3227 Hey Guys, I have to write a rock, paper, scissors program and I'm having difficulty with doing so. The majority of the program has already been built, I just have to code the functions. This is the link to the website that shows the details of the program: http://faculty.cs.niu.edu/~byrnes/csci240/pgms/240pgm5.htm Attached is an image of the functions that I have to code. 3228 Hey guys, I have a stupid question. I want to delete a file in Windows Explorer but I don't know to do that. So I need a tutorial, please help me. Thanks 3229 Hey guys, really lost here. Any help would be awesome. Ill put the question down below and thanks: Write an assembly language program that corresponds to the following C++ program: #include using namespace std; int num1; int num2; main () { cin >> num1 >> num2; cout << num2 << endl << num1 << endl; return 0; } 3230 Hey guys! I am new to C++ and I have an assignment coming up that I can't seem to nail down. Actually, I am very lost and would like some help. We were told to write a program that will first, prompt the user to input a positive integer (check). Then, store that integer in a variable called initial_num (check) -------?---------L?--------O?------S?-----T?-----------? Use loops and if statements (or switch statements) in order to output every positive integer (num) from one to intital_num. then, test each num to see if it is prime or not. (in doing so, output the numbers that evenly divide the num) ---------> I can't get past this part to get to the next part-----------> after outputting these numbers, send out a message stating whether or not num is prime. your code should execute as shown below: Testing 1 > 1 1 is not a prime number Testing 2 > 12 2 is a prime number 3.. .. 4.. .. .. .. 7 Press any key to continue... _______sample run 2_______ Testing 1 > 1 1 is not a prime number Testing 2 > 12 2 is a prime number 3.. .. 4.. .. .. .. testing 7 > 17 7 is a prime number 8 9 10 11 12 > 1 2 3 4 6 12 12 is not a prime number Press any key to continue..... Seems pretty basic. Also, any youtube beginner links or any resource you can throw my way to help me learn this language would be much appreciated! 3231 Hey guys, any help would be great. Thanks for everything and Ill post the question down below: EDIT: I dont know if it matters but im using the Pep 8 Write an assembly language program that prints your first name on the screen. Use the .ASCII pseudo-op to store the characters at the bottom of your program. Use the CHARO instruction to output the characters. 3232 Hey guys, any help would be great. Im using the Pep 8 if that has any affect on the question. Ill put it down below: Convert the following machine language instructions into assembly language, assum- ing that they were not generated by pseudo-ops: (a) AAEF2A 3233 Hey guys any help would be awesome. Im really stuck, Ill put the question below and thanks for any help: EDIT : Im using the PEP 8 Write an assembly language program that corresponds to the following C++ program: #include using namespace std; int num1; int num2; main () { cin >> num1 >> num2; cout << num2 << endl << num1 << endl; return 0; } 3234 Hey guys, any help would be awesome. I basicaly need to know what this Pep/8 program does. I can get it to run on Pep/8 but this is exactly how it is in the book. Ill put the program below: 0000 040009 BR main 0003 0000 n1: .BLOCK 2 ;#2d 0005 0000 n2: .BLOCK 2 ;#2d 0007 0000 n3: .BLOCK 2 ;#2d ; 0009 310005 main: DECI n2,d 000C 310007 DECI n3,d 000F C10005 LDA n2,d 0012 B10007 CPA n3,d 0015 08002A BRLT L1 0018 310003 DECI n1,d 001B C10003 LDA n1,d 001E B10007 CPA n3,d 0021 080074 BRLT L7 0024 040065 BR L6 0027 E10007 STA n3,d 002A 310003 L1: DECI n1,d 002D C10005 LDA n2,d 0030 B10003 CPA n1,d 0033 080053 BRLT L5 0036 390003 DECO n1,d 0039 390005 DECO n2,d 003C 390007 L2: DECO n3,d 003F 00 STOP 0040 390005 L3: DECO n2,d 0043 390007 DECO n3,d 0046 040081 BR L9 0049 390003 L4: DECO n1,d 004C 390005 DECO n2,d 004F 00 STOP 0050 E10003 STA n1,d 0053 C10007 L5: LDA n3,d 0056 B10003 CPA n1,d 0059 080040 BRLT L3 005C 390005 DECO n2,d 005F 390003 DECO n1,d 0062 04003C BR L2 0065 390007 L6: DECO n3,d 0068 C10003 LDA n1,d 006B B10005 CPA n2,d 006E 080049 BRLT L4 0071 04007E BR L8 0074 390003 L7: DECO n1,d 0077 390007 DECO n3,d 007A 390005 DECO n2,d 007D 00 STOP 007E 390005 L8: DECO n2,d 0081 390003 L9: DECO n1,d 0084 00 STOP 0085 .END 3235 Hey guys, this is my first question. I want to download videos from Youtube, so how can I do that? Please help me. Thanks 3236 Hey guys, I download movie from internet but I don't know how to join file. It format: Movie.avi.001 - Movie.avi.002 3237 The hexagon game involves two players who gradually construct a six-vertex undirected graph with solid and dashed edges; Player 1 adds solid edges, whereas Player 2 uses dashes. The players begin with some initial six-vertex graph, which already has a few solid and dashed edges (see the picture on the left), and add new edges one by one; Player 1 makes the first move. At each move, a player has to add a new edge between two vertices that are not connected by any old edge. If Player 1 constructs a solid-line triangle, he loses the game; similarly, a dashed triangle means a loss of Player 2. For example, if the game ends as shown in the rightmost picture, then Player 2 has lost since he has constructed the triangle A????11-2-5.A????1 Note that this game cannot end in a draw because a full six-vertex graph always has a solid or dashed triangle. Your task is to write a program that determines which player wins the game if both players use a perfect strategy. 3238 Can you help me with this? Write a Java program that includes a method called pay that accepts two parameters: A real number for an employee's hourly wage and an integer for the number of hours the employee worked that day.The method should return how much money to pay the employee for this day. For example, the call pay (5.50, 6) should return 33.0. The employee should receive "overtime" pay of 1.5 times the normal hourly wage for any hours above 8. For example, the call pay (4.00, 11) should return 50.0 (calculated as (4.00 * 8) + (6.00 *3). Include in the main method of this program four calls to the pay method. Two calls, each one using the example data given above and two calls, each one using data that you determine. 3239 Can you help me with this? Write a Java program that includes a method called pay that accepts two parameters: A real number for an employee's hourly wage and an integer for the number of hours the employee worked that day. The method should return how much money to pay the employee for this day. For example, the call pay (5.50, 6) should return 33.0. 3240 Any help would be awesome, really stuck. Thanks agian. 10. In a doubly linked chain , each node can point to the previous node as well as to the next node. Figure 4-9 shows a doubly linked chain and its head pointer. De?ne a class to represent a node in a doubly linked chain. 12.List the steps necessary to remove the ?rst node from the beginning of the doubly linked chain shown in Figure 4-9 . 3241 Help me solve this problem Show transcribed image text Give context-free grammar that generate The following language. In all part summation = {0,1} Make a state diagram of pushdown automation 3242 help me this solve the following two's comple ment arithmetic problems show your work in binary. note wheather each answer is valid or invalid a) 01101100 + 00110100 valid/invalid? b)11101100-11111100 valid/invalid? c)11010101 - 00111000 valid/invalid? d)11111111 + 11111111 valid/invalid? e)00000001 + 11111111 valid/invalid? f) 01011001 - 10100011 valid/invalid? 3243 Help? 3244 help plese Please include Word document with design (pseudo-code), assumptions, and test cases too. Concepts tested by this program: Create a worker class Create a GUI driver Frame Panel Event programming Radio Buttons Check Boxes Textfields Labels Buttons JOptionPane. showMessageDialog Hartatak Hamburger Hartatak Hamburger sells 3 things: hamburgers, cheeseburgers and double cheeseburgers. Their motto is A????1Free use of our defibrillator with every order.A????1 Write a Java application that calculates the subtotal, tax and total of an order. The cost for a hamburger is $4.95, a cheeseburger is $5.95 and a double cheese burger is $6.95. You can add 0 or more condiments: ketchup, tomato, onion, lettuce, mayonnaise, or mustard at a cost of $.25 each. The sales tax on an order is 7.85%. Worker Class - BurgerOrder The class BurgerOrder will contain: 1. instance variables 2. constants. Use A????1named constantsA????1 for any literal values that will not change during program execution. 3. getter and setter methods 4. A method to calculate the subtotal, tax and total price of the order. 5. A method to return a string that could be used to print a receipt. 6. You may add any additional methods to find necessary for your design GUI Driver A????1 Frame and Panel. You may use the GUI Template as an example or starting point for your code. - For each order, the user selects one Hamburger, Cheeseburger or Double Cheeseburger and zero or more of the condiments. A????1-When the user clicks the Place order button, the application displays the subtotal, tax, and total due for an order. -When the user closes the frame or presses the Exit button, the application exits. A????1 The Hamburger radio button should be initially selected. A????1 The condiments are $0.25 each. A????1 Display the Receipt in an JOptionPane.showMessageDialog. A????1 Display subtotal, tax and total due in currency format ** buttons are in gridlayout Templates are given /** this is the Data manager * The DataManager class should never depend on the GUI, but rather the reverse. * So the DataManager methods should not use the GUI directly. If you want data * to get from the user to the manager, have the GUI get the data, and call the manager * with the data that the GUI got from a text field or other data structure. * @author ralexander * */ public class DataManager { DataManager() { //TO DO: initialize the manager } /** * This method illustrates how the GUI can pass data to the manager * @param text a String entered by the user in a JTextField */ public String doSomething(String text) { return "Data Manager receives text from the user... "+text; } public int sendSomething() { return 0; } } --------------------------------------------------------------- // this is the driver class import java.awt.BorderLayout; import java.awt.Container; //import java.awt.Graphics2D; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JPanel; /** * This application provides a simple template for GUIs, showing several examples of * buttons, radio buttons, JLabels, JTextFields, etc. * MainPanel uses a BorderLayout for it's five panels, and the center panel uses * a GridLayout of size 3,3, to display 7 JLabels. * @author CMSCAuthor * */ public class Driver extends JFrame { JPanel mainPanel; /** * Driver() is the constructor for the top-level GUI class. It simply * calls the MainPanel constructor and adds it to the JFrame's content pane */ public Driver() { setTitle("......"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = getContentPane(); mainPanel = new MainPanel(); contentPane.add(mainPanel); } /** * The main method for the GUI example program * @param args not used * @throws IOException */ public static void main(String[] args) throws IOException{ JFrame frame = new Driver(); frame.pack(); frame.setVisible(true); } } -------------------------------------------------- // This is main panel import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; /** * This panel is the basic panel, inside which other panels are placed. * Before beginning to implement, design the structure of your GUI in order to * understand what panels go inside which ones, and what buttons or other components * go in which panels. * @author CMSCAuthor * */ public class MainPanel extends JPanel{ private JPanel buttonPanel, dataPanel, leftPanel, rightPanel, topPanel; private JButton otherButton, exitButton, callMgrButton; private JTextField exampleTextField; private JLabel exampleLabel; private JRadioButton radioButton1, radioButton2, radioButton3; private String userText = ""; //The manager is the way the GUI communicates with the worker code private DataManager dataManager; /** * The MainPanel constructor sets up the entire GUI in this template. Remember to * wait to add a component to its containing component until the container has * been created. This is the only constraint on the order in which the following * statements appear. */ MainPanel() { //make the main panel's layout be a BorderLayout setLayout(new BorderLayout()); //create the dataManager instance dataManager = new DataManager(); //create the exitButton exitButton = new JButton("Exit"); exitButton.setMnemonic('E'); exitButton.setToolTipText("Exit the program"); //create a listener for the exit button exitButton.addActionListener(new ButtonListener()); //create another button otherButton = new JButton("Some other button"); otherButton.setToolTipText("Select this to see what the user entered"); //create a listener for the other button otherButton.addActionListener(new ButtonListener()); //create the mgrButton callMgrButton = new JButton("Call the Manager"); callMgrButton.setToolTipText("Show how to access the Manager from the GUI"); //create a listener for the exit button callMgrButton.addActionListener(new ButtonListener()); //create an example JTextField and an example JLabel exampleTextField = new JTextField(10); exampleLabel = new JLabel("...Example JLabel..."); //create three radio button instances radioButton1 = new JRadioButton("button 1"); radioButton2 = new JRadioButton("button 2"); radioButton3 = new JRadioButton("button 3"); //create a group to make the radio buttons mutually exclusive ButtonGroup radioButtonGroup = new ButtonGroup(); radioButtonGroup.add(radioButton1); radioButtonGroup.add(radioButton2); radioButtonGroup.add(radioButton3); //create a single listener for the radio buttons to share; note that a different //example is used for the JButtons, where a separate listener object is //created for each JButton. Either way works fine, although the way it is done //here is more efficient. RadioButtonListener radioButtonListener = new RadioButtonListener(); radioButton1.addActionListener(radioButtonListener); radioButton2.addActionListener(radioButtonListener); radioButton3.addActionListener(radioButtonListener); //create the buttonPanel buttonPanel = new JPanel(); //These dimensions don't always have the final say in determining the panel's size //It basically is the default if other constraints allow buttonPanel.setPreferredSize(new Dimension(50,50)); //The border around each panel is optional. //buttonPanel.setBorder(BorderFactory.createTitledBorder("...