EEE481 Homework 7

Problem 1
Consider the cart and pendulum system describing the evolution of the cart velocity, the
pendulum angle and the pendulum angular velocity (see details in
http://tsakalis.faculty.asu.edu/notes/models.pdf). The linearized equations around the unstable
equilibrium (angle 180deg, zero input, zero velocities) for the deviations of the state variables
from the linearization point, are:
(???? + ????)
????????
???????? = −???????????? + ????ℓ
????????
???????? + ????
????????
???????? = ????
????ℓ
2
????????
???????? = −???????????? + ????????ℓ???? + ????ℓ
????????
????????
The various constants are (all values in SI): friction coefficients ????????, ???????? = 0.1, pendulum mass ???? =
0.2, pendulum length ℓ = 0.2, cart total mass ???? = 0.4, gravitational constant ???? = 9.81.
The Force term is applied by the cart wheels driven by a DC motor with a model from the
applied voltage (say, -5:5Volts) to the force
???? = ???????? + ????
????????
???????? + ????????????????, ???????????????? = ????????, ???? =
????????
????
Where the back-emf is taken as proportional to the motor angular velocity, which is also
proportional to the cart velocity, while the motor current generates the torque that is converted
to force by the wheels of radius r. The constants are motor resistance ???? = 5, inductance ???? =
0.1, emf/torque-constant ???? = 0.3, and wheel radius ???? = 0.1.
We want to design a controller for this system to stabilize the inverted pendulum and be able to
follow commands for the cart speed. We want to use a sequential approach where we first
stabilize the angle with an “inner-loop controller”. Then form the inner closed loop and design
an “outer loop controller” for the cart velocity.
There are two difficulties associated with this problem. One is that the angle subsystem has a
RHP pole and a zero at the origin. Its stabilization requires a controller with a RHP pole. We can
solve this as a modified PID problem where instead of the integrator we use a RHP pole
determined iteratively.
The other difficulty is technical, namely, how to create the various systems and loops without
leaving stray pole-zero cancellations (possibly in the RHP) and without resorting to tedious hand
calculations. (One approach for this is to implement the model in Simulink and use the “linmod”
command, and the other -taken here- is to work with the state space model using the
“feedback” command.)
1. Form the state-space description of the system with one input (Voltage) and three
outputs, (velocity, angle, Voltage). It is convenient to keep the voltage as an output to
make it easy to simulate with Matlab commands. We want to implement the controller
in DT with a sampling rate 100Hz. For this system, it is more convenient to follow the wplane approach, find the ZOH equivalent of the plant now and convert to the w-plane
and do not have to do corrections during the subsequent iterations.
2. Extract the angle subsystem (e.g., P(2), if the angle is the 2nd output) and design an
“inner-loop” stabilizing controller ???????? =
????(????????????+1)
2
(????−????)(????????????+1)
, where “????” and the crossover
frequency are to be iterated to achieve a reasonable response (crossover should be
larger than the RHP poles, “????” should not be larger than the RHP pole). PM is to be
selected but large values are not very realistic (consider 40-50).
3. Form the inner loop system.
Hint: The Matlab command is
>> Pi=feedback(P*Ci,ss([1]),1,2);
The second argument is the feedback system, the third output is the index of the
P-inputs connected to the C-outputs (1, there is only one) and the fourth output is
the index of the P-outputs connected to the C-inputs (“2” for the angle being the
2
nd output). Pi is a new system that has the same number of inputs and outputs,
the input is angle set-point and the outputs are the outputs of P.
4. Design a DT PID controller for the velocity (1st output, so P(1) subsystem).
Prefilter considerations: For step inputs, the linear control input becomes very large and
the angle can overshoot a lot. In practice, that is a problem because the input is limited
by the voltage constraints and if the angle becomes too large, the inverted pendulum will
fall (because of acceleration constraints). Here, it may be beneficial to consider a
prefilter, e.g., a lowpass filter ???? =
1
(????????+1)
either first or second order roughly at the
bandwidth of the outer loop crossover. Design the controller for the filtered plant and
then include the filter in the controller. The objective is to keep the control input
amplitude and the angle excursions reasonable, without slowing down the loop too
much. For this size of cart-and-pendulum, we expect stabilization in a few seconds. Also,
keep in mind that the outer loop system has “negative gain”.
5. Form the outer loop system as in Part 3 and check the responses.
>> Po=feedback(Pi*Co,ss([1]),1,1);
The last argument “1” assumes that the first output is the cart velocity.
6. Since all the design was done in the w-plane, it is straightforward to discretize the
controllers (using Tustin) and form the feedback loops with the “feedback” command.
Provide the transfer functions of your controllers and plots of the relevant time and
frequency responses.
Problem 2
Consider the system
????(????) =
−0.4???? + 4
????
2 + 4???? + 4
1. Design a DT controller using the w-plane method for crossover 4 rad/s, PM = 45 degrees
and a sampling time of 10 Hz.
2. For an additive measurable disturbance at the plant output with transfer function
????(????) =
1
????+1
, design a DT feedforward controller H(z) to reduce the transient component
of the DT PID designed in Part 1. Use the “naïve” approach and comment on the benefit
of such a component for this case.
Problem 3
Consider the cart and pendulum system of Problem 1.
1. Design a DT state estimator (observer) for the system with outputs cart velocity and
pendulum angle. It is convenient here to use a LQ approach because of the multiple
outputs. Choose the estimator gain to achieve convergence faster than one second.
Hint: The state estimator has the form ????????+1 = ???????????? + ???????????? + ????(???????? − ????????) where
x,y are the estimated states and outputs and m is the measurements (the plant
y_k). The design equations are implemented in Matlab by the function “dlqr”
???? = ????????????????(????

, ????

,???? ∗ ????
2 + ???????? ∗ ???? ∗ ????

,????)′
The design parameters have been simplified to to depend only on a gain factor
mu (such that larger mu yield higher bandwidth) and the sample time T. The
performance is characterized by eigenvalues of the observer eig(A-L*C) and its
Sensitivity (error system)
???????? = [???? − ????????, ????, ????, −????]
2. Design a DT state feedback to stabilize the cart-and-pendulum system. You may add an
offset to the velocity measurement to enable convergence to a nonzero velocity but do
not worry about integral action control.
Hint: The LQR problem minimizes the cost of states (x’Qx) and control inputs
(u’Ru), for the system
????????+1 = ???????????? + ????????????
Its solution is the linear state feedback
???????? = −???????????? => ????????+1 = (???? − ????????)????????
It is implemented in Matlab by the function “dlqr”, with syntax
???? = ????????????????(????, ????, ????

∗ ????, ????????)
The design parameters are Q = C’C (penalizing the output) and ???? which is the
penalty on the control input and serves as an inverse-gain parameter. When ????
decreases the controller bandwidth increases. The controller performance is
characterized by the eigenvalues of A-BK and the Sensitivity of the input to
disturbances at the plant input
???????? = [???? − ????????, ????, ????, −????]
3. Combine the state feedback with the state estimator to obtain an output feedback
controller. Illustrate the time and frequency responses of the controller.
Hint: The “model-based” controller uses the state feedback with the states
replaced by their estimates. The combined controller is (D=0)
????????+1 = ???????????? + ???????????? + ????(???????? − ????????
) ; ???????? = −???????????? ; ???????? = ????????????
=> ????????+1 = ???????????? − ???????????????? − ???????????????? + ????(????????
) ; ???????? = −???????????? ;
Thus, for negative feedback, the controller state-space representation becomes
[???? − ???????? − ????????, ????,????, 0]
The controller has two inputs, the measured outputs of the system (m_k), and
one output, the control u_k. An external input (scaled reference) may be added
to the measurement m_k (i.e., the y_k of the plant). However, tracking of a
setpoint requires integral action which is not considered here.
Problem 4
Consider the cart and pendulum stabilized by the inner-outer PID controller of Problem 1. In the
context of refining the plant models in case of a change, we want to estimate the plant transfer
functions based on input-output data. The system is, of course, unstable and data cannot be
collected without a stabilizing controller.
Use the closed-loop system of Problem 1 with input reference velocity and outputs angle,
velocity, and voltage (control input). Apply a reference input (Random or Square Wave and
combinations) with maximum amplitude around 1. Add random noise to the outputs (angle,
velocity) at a level of 0.02 ~ 0.5 degrees.
N=10000;
t=(0:N-1)’*T;
rn=(rand(N,1)-.5); n1 =(rand(N,1)-.5)*0.02; n2 =(rand(N,1)-.5)*0.02;
r=sign(sin(6.28/10*t))/2+rn;
Y=lsim(Pdo,r); % Pdo created in Problem 1
plot(t,Y)
u=Y(:,3); y1=Y(:,1)+n1; y2=Y(:,2)+n2;
Design a batch parameter estimator to identify the transfer functions from the plant input “u” to
each output “yi” (angle, velocity). Look at the system equations to decide the order of the
estimated transfer functions. Try different filters for the input-output pairs and compare with
the known transfer functions. Could the estimates be used to redesign the controller?

US History Case

For this assignment you will read “Crossing the Great Plains by Ox-Wagons” by Harriet Scott Palmer who made the trip in 1852 at the age of 11. You’ll find it at: http://www.legendsofamerica.com/we-crossingplains.html

Respond to the following questions in anessay of at least 350 words:

After reading both the textbook and Palmer’s story what are your general impressions about making such a long and hazardous journey halfway across the continent?

x

Which account did you enjoy reading the most? Why?

x

Which of Palmer’s particular experiences impressed you the most? Why?

x

In comparison with other accounts of crossing the Oregon Trail Palmer’s journey seems to have been typical or perhaps even less eventful than the thousands of others who made the trip in similar fashion. Do you think that Americans today still have what it takes to meet and overcome similar challenges? Why or why not?

x

Did these readings change your perceptions of the settlement of the West? If so, in what way?

business management

Place of Submission is Blackboard.

• Weight 15 Marks

Learning Outcomes:

1. Describe the place of small business in history and explore the strengths and weaknesses of small business.(LO 1)

2. Design a solid projected financial plan and conduct a breakeven analysis for a small company. (LO 3)

3. Demonstrate the ability to deliver and communicate marketing massages in coherent and professional manner. (LO 5)

4. Illustrate the ability to think independently and systematically on developing a viable business model.(LO 6)

Assignment Workload:

This assignment is an individual assignment.

An entrepreneur Start-up

Business Plan

A business plan is any simple plan, not only limited to the business start-up plan that helps the management to understand the current situation of the enterprises (strengths, weakness, opportunities and threats) and look forward into the future. A start-up plan is a business plan which consists of the mission, vision, objectives and action plans for the future of the new enterprises while the business plan drawn during the operation of the firm is vital for running the firm effectively, acquire new customers, partners, loans and so on. According to Fiore (2005), a business plan involves two dimensions; an organizing tool to simplify and clarify your business goals and strategy, the second one is a selling document that sells the business idea and shows that a product or a service can make a profit and attract funding and company resources.

Imagine you started a new business as an entrepreneur in Saudi Arabia. Briefly mention the specific steps which you consider necessary to a successful business plan.

Please, think and share information on the following items:

1. Owners, capital structure and company profile (3 Marks)

a. Your Business Name, Address, E‐Mail

b. Form of ownership: What is the legal structure? Sole proprietor, Partnership, Corporation….

C. Investment capital

2. Company Business Description (300 – 400words)

A. Scope and type of business (5 Marks)

What business will you be in? What will you do? What market segment will you choose?

• Business idea: what is your big idea? Is it a product or a service? What makes your idea different?

• Mission Statement

• Company’s short-term and long-term goals and objectives.

• Target market and demographics: Who will your customers be? Where do they live? What is your target market passionate about?

B. Business Philosophy (4 Marks)

What is important to you in your business?

• Describe your Industry: Is it a growth industry? What long-term or short-term changes do you foresee in the industry? How will your company take advantage of it?

• Describe your most important company strengths and core competencies: What factors will make the company succeed? What do you think your major competitive strengths will be? What background experience, skills, and strengths do you personally bring to this new venture?

• Risk Assessment: Evaluate the strengths and weaknesses of your business using SWOT.

•Who is your competition and how do you beat them?

3. Products and Services (3 Marks)

a. Briefly discuss your products or services (Technical specification).

b. Size of business: how many employees? How many offices and retail facilities?

c. What factors will give you competitive advantages or disadvantages? Examples, include level of quality or unique or proprietary features.

Logistics and Supply Chain Management

 The Assignment must be submitted only in WORD format via allocated folder.

• Assignments submitted through email will not be accepted.

• Students are advised to make their work clear and well presented, marks may be reduced for poor presentation. This includes filling your information on the cover page.

• Students must mention question number clearly in their answer.

• Late submission will NOT be accepted.

• Avoid plagiarism, the work should be in your own words, copying from students or other resources without proper referencing will result in ZERO marks. No exceptions.

• All answered must be typed using Times New Roman (size 12, double-spaced) font. No pictures containing text will be accepted and will be considered plagiarism).

• Submissions without this cover page will NOT be accepted.

Logistics Management

ASSIGNMENT -1

Submission Date by students: Before the end of Week- 6th

Place of Submission: Students Grade Centre

Weight: 15 Marks

Learning Outcome:

1. Demonstrate a deep understanding of the logistic function concepts and theories as well as supply chain management strategies.

2. Demonstrate the ability to understand complex issues pertaining to supply chain integration and strategic supply chain partnership.

Assignment Workload:

This assignment is an individual assignment.

Critical Writing

The purpose of this assignment is to identify and apply Logistics and Supply Chain Management concepts/tools to suggestlogistics performance priorities. To this purpose, you should search and review about these companies through secondary available information. Think about how you can apply the concepts/tools that you learned in this course.

Write about the logistics performance prioritiesof any ONEof your choicein Covid 19 restrictions. Explain why you have come to your conclusions:

1) A low-fare Airline FLYADEAL

2) A fast-food chain Such as Albaik

The Answer must follow the outline points below:

1. Executive summary (3 Mark, Max word count 450-500)

– Summarize what is logistics performance priorities,and what Logistics and Supply Chain Management concepts/tools applied to achieve the company’s objective.

2. Background information(3 Mark, Max word count 450-500)

– Briefly introduce the company background (e.g., name, products, business size, location, internal/external interesting facts, etc).

3. Problem Description(3 Mark, Max word count 450-500)

– Describe the objectives clearly and specifically.

– The objective may involve either logistics decision-making or process improvement.

4. Application of logistics and SCM concepts/tools thatwere applied(3 Mark, Max word count 450-500)

– Describe what specific logistics and Supply Chain Management concepts/tools be applied to achieve the objective. This section should make it clear that you understand the concepts/tools you are about to use.

5- Conclusion and results(2 Mark, Max word count 300400)

– Analyze the expected results the proposed solution.

6. References at least 7-10. (1 Marks)

risk management

Part 1

Discussion #1:

Write a 250- to 300-word response to the following:

  • How is the risk management issue that you selected currently being addressed?
  • What risk management gaps exist in health care or hospital risk management? Based on industry literature, how would you address these gaps?
  • What strategies would you use to communicate the risk management gaps with leadership and the rest of the team?
  • Include your own experience as well as two citations that align with or contradict your comments as sourced from peer-reviewed academic journals, industry publications, books, and/or other sources. Cite your sources using APA formatting. If you found contradicting information to what your experience tells you, explain why you agree or disagree with the research.

 

Discussion #2:

Write a 250- to 300-word response to the following:

  • Discuss the Nebraska Hospital Medical Liability Act (NHMLA), the Nebraska Excess Liability Fund (NELF), and medical malpractice laws.
  • Identify how medical malpractice laws protect providers.
  • Discuss how medical malpractice laws impact a patient’s ability to receive compensation when there is proof of medical malpractice and resulting harm.

 

Part 2

Student Responses:

Student Response 1: Student response 1: Review the classmates’ posts and respond to at least one in a minimum of 150 words.Explain why you agree or disagree. Then, share an example from your professional experience to support your assertions.

There is compelling evidence of the negative impacts of language barriers and reliance on untrained interpreters on health and healthcare (Bowen et al., 2010). Not having available trained translators when patients come to the clinic is a risk management issue. Language barriers result in a host of problems that cause risk to the patients like delayed presentation for care in non-urgent situations; avoidance of needed care; increased risks of misdiagnosis; poorer patient understanding of and adherence to prescribed treatment; lower patient satisfaction; lower quality of care; increased risk of experiencing adverse events; poorer management of the chronic disease; and poorer health outcomes (Bowen et al., 2010). Instead of investing, most healthcare systems rely on phone translators and family members as a cost-effective way to address linguistic issues. The risks of language barriers and the use of services of untrained interpreters to both the health of individuals and the health system itself have been well documented (Bowen et al., 2010). Addressing language barriers is the one strategy for improving organizational cultural competence with theoretical and practical evidence linking it to improved health outcomes (Brach & Fraser, 2000).

 

The first step to communicating risk would be to engage the risk manager and make them aware of the issue and how the unavailability of trained translators presents a threat to providing quality patient care. Presenting well-documented evidence would be the strategy used to inform leadership so they understand the importance of hiring skilled medical translators. An outline would be provided, depicting the financial implications of failing to address language barriers appropriately: increased use of high-intensity services and decreased use of primary care services; costs related to misdiagnosis and repeat visits; and costs of longer lengths of stay (Bowen et al., 2010). Thus, justifying how translation services could significantly reduce linguistic barriers, changing the healthcare experience for non-English speaking patients and improving their health outcomes.

 

References:

Bowen, S., Gibbens, M., Roy, J., & Edwards, J. (2010). From ‘multicultural health to ‘knowledge translation’. Rethinking strategies to promote language access within a risk management framework. Jostrans14, 145-164. https://jostrans.org/issue14/art_bowen.pdf

 

Brach, C., & Fraserirector, I. (2000). Can cultural competency reduce racial and ethnic health disparities? A review and conceptual model. Medical Care Research and Review57(1_suppl), 181-217. https://doi.org/10.1177/1077558700057001S09

 

Student Response 2: Student response 1: Review the classmates’ posts and respond to at least one in a minimum of 150 words.Explain why you agree or disagree. Then, share an example from your professional experience to support your assertions.

The Nebraska Hospital Medical Liability Act (NHMLA) and the Nebraska Excess Liability Fund (NELF) are significant components of medical malpractice laws in Nebraska, which aim to protect healthcare providers and patients alike (Adomako et al., 2018). In Book II, “The Aftermath of the Nebraska Outbreak,” of A Never Event, the implications of these laws are explored in the context of the Nebraska healthcare system.

The NHMLA was enacted in Nebraska to regulate medical malpractice claims against healthcare providers, including physicians, nurses, and hospitals. It establishes guidelines for the submission and resolution of medical malpractice claims, including the requirement of a certificate of merit, which must be obtained from a qualified expert, stating that there is a reasonable basis for the claim (Nebraska Revised Statutes, §§ 44-2801 to 44-2829). The NHMLA also sets a cap on damages, limiting the amount that can be awarded to a plaintiff in a medical malpractice lawsuit, which varies depending on the type of defendant and the nature of the injury (Nebraska Revised Statutes, §§ 44-2825).

On the other hand, the NELF is a state-run excess liability fund that provides additional coverage to healthcare providers beyond the limits set by the NHMLA. Healthcare providers fund it and provide a source of compensation for patients who have suffered harm due to medical malpractice (Nebraska Department of Insurance, 2019).

These laws aim to protect healthcare providers by limiting their liability and providing them with a predictable system for resolving medical malpractice claims. By requiring a certificate of merit, the NHMLA helps to ensure that claims are based on expert opinions, reducing the likelihood of frivolous lawsuits (Adomako et al., 2018). The cap on damages limits the financial exposure of healthcare providers, preventing excessive payouts that could financially burden providers or impact their ability to continue practicing medicine (Nebraska Revised Statutes, §§ 44-2825).

At the same time, these laws also impact a patient’s ability to receive compensation when there is proof of medical malpractice and resulting harm. The cap on damages set by the NHMLA can limit a patient’s compensation, even if the harm is severe (Adomako et al., 2018). This may result in patients receiving less than the full extent of their damages, including medical expenses, lost wages, and pain and suffering. The requirement of a certificate of merit may also present a barrier for patients in obtaining legal representation and pursuing their claims, as it adds steps and cost to the legal process (Nebraska Revised Statutes, §§ 44-2801 to 44-2829).

Furthermore, the NELF, as a state-run fund, may also have limitations regarding the amount of compensation it can provide or the types of cases it can cover. Patients who cannot obtain compensation from the NELF may face challenges in seeking redress for their injuries (Nebraska Department of Insurance, 2019).

In conclusion, the NHMLA, NELF, and medical malpractice laws in Nebraska aim to balance protecting healthcare providers and ensuring patients have access to compensation for medical malpractice (Nebraska Department of Insurance, 2019). These laws provide a structured framework for handling medical malpractice claims. Still, they may also limit a patient’s ability to receive total compensation for proven medical malpractice and resulting harm. Healthcare providers and patients alike need to understand the intricacies of these laws and seek legal counsel when navigating medical malpractice claims in Nebraska.

Chemical Engineering

1) One scenario that has been examined in the failure investigation of the Space Shuttle Columbia is the impact of a chunk of polyamide foam of mass of 1.211 kg, of dimensions of 0.508 m wide x 0.406 m long x 0.152 m tall, traveling at 457.3 m/s with a thermal heat-shielding tile, essentially composed of silica (SiO2).

 

  1. A) (4 pts.) Calculate the kinetic energy with which the polyamide foam hit the silica tile.

 

 

 

 

  1. B) (7 pts.) Use your textbook to determine silica‘s modulus of elasticity (E), the yield stress (YS), the

ultimate tensile strength (UTS), percent elongation (the amount of strain multiplied by 100%) at

failure, the coefficient of thermal expansion (CTE), and the fracture toughness (also known as the

critical stress-intensity factor).  Use SI units.  Assume the worst case.

 

 

 

 

 

 

 

  1. C) (6 pts.) Assume the ultimate compressive strength is equal to the ultimate tensile strength. Sketch the

stress-strain curve for silica along with the YS, UCS, MOE, RS, and the strain at the yield stress

and the strain at failure.

 

 

 

 

 

 

 

 

 

  1. D) (7 pts.) Assume that the silica is highly efficient at transferring the load from the point of

impact and distributing the load equally over the whole tile (Cross-sectional area = .005 m2 with a

thickness of 0.05 m).  Calculate the amount of energy in Joules that a silica tile would be capable

of absorbing without plastically deforming.

 

 

 

 

 

 

 

 

 

 

 

 

 

  1. E) (1 pt.) Comparing your results of parts D and A, would the silica tile elastically absorb the impact?

 

  1. F) (4 pts.) Compute the amount of plastic deformation that the silica tile can absorb.

 

 

 

 

  1. G) (4 pts.) If the silica has a 1 mm crack from a previous incident, given the numbers from part

B, and assuming Y = 1, calculate the maximum amount of stress that the tile could take now.

Would you be safe using a shuttle tile with a 1 mm crack in it? Provide a brief explanation using

some of the quantities you have either looked up or have calculated.

 

 

 

 

 

 

 

2) (10 pts.) An ion gauge with a glass/metal interface (see photo) is heated under vacuum.  The interface heats up such that the glass side (“Glass, borosilicate (Pyrex)” in the accompanying tables) heats up from 298 K to 340 K, but the annealed “Super Invar” (under Miscellaneous Nonferrous Alloys” heats up only to 310 K.  Using Appendix B, determine a) the strain that the glass experiences, b) the strain that the Super Invar metal experiences, and c) the difference in strain (the strain across the interface between the two materials.  Do either the glass or the metal experience enough strain to be plastically deformed?  Do either the glass or the metal experience enough strain such that the glass/metal interface breaks?

 

 

 

 

 

 

 

3)  A) (5 pts.)  List a set of causes as to why your teeth might fail.

 

 

 

 

 

 

 

  1. B) (5 pts.) Associate each cause from part A with one or more failure mechanisms in part B.

 

 

 

 

 

 

 

  1. C) (5 pts.) What might you do to prevent premature tooth failure?

 

 

 

 

 

 

 

4)  You are part of a team designing a process and robots to mine the moon’s soil, do a very preliminary separation of such soil to separate aluminum-rich particles by size (Assume they will be smaller.) from other lunar soil, and then use a flying robot to transport the Al-rich particles to an aluminum refinery elsewhere on the moon’s surface.

  1. A) (5 pts.) List a set of causes as to why your process and robots might fail.

 

 

 

 

 

 

 

  1. B) (5 pts.) Associate each cause from part A with one or more failure mechanisms in part B.

 

 

 

 

 

 

 

  1. C) (5 pts.) What might you do to prevent premature failure of any part of the lunar mining and refining?

 

 

 

 

 

 

5)  Some fish can live at depths of 5000 meters.  Assume gravity is 9.81 m/s2.  Assume fish and human        bone have a yield stress of 100 MPa, a modulus of elasticity of 1500 MPa, and a Poisson’s ratio of

0.3.  Assume the density of salt water and bone are 1025 kg/m3 and 1900 kg/m3, respectively.

 

  1. A) (3 pts.) Calculate the bulk modulus of the fish.

 

 

 

 

 

 

  1. B) (3 pts.) Calculate the volumetric strain on the fish at a depth of 5000 meters.

 

 

 

 

 

  1. C) (3 pts.) Assuming (incorrectly) that the fish is isotropic, calculate the amount of stress on the fish, and determine whether or not the fish bone is plastically deformed.

 

 

 

 

 

  1. D) (3 pts.) Calculate the shear modulus of the fish bone.

 

 

 

 

6) (15 pts.) You have prepared a molybdenum nitride by cooling a 6 wt. % N/94% Mo mixture infinitely slowly.  A) Sketch what the material will look like after that infinitely slow cooling.  B) What is undesirable about the material in part A? C) Thoroughly describe a process, being specific about temperatures and endpoints (but not exact times), to best remediate the problem described in parts A and B.

 

Acquisition and the post-combination financial statements

Cool Care, an SEC registrant and a hospital operator in the United States, acquired all of the outstanding common stock of Healthy Hearts, an unrelated third party that operates specialty hospitals focused exclusively on cardiology. After the acquisition, Healthy Hearts become a wholly owned subsidiary of Cool Care (the “Acquisition”).

Several years before the acquisition, in a public offering, Healthy Hearts raised capital to expand and upgrade its operating rooms by issuing $400 million aggregate principal amount of 7.00% senior notes due in 2020 (the “Notes”). In performing due diligence and assessing the terms of the Notes, Cool Care determined that it could obtain cheaper financing and instructed Healthy Hearts to make a tender offer for any and all its outstanding Notes (the “Tender Offer”). Accordingly, contemporaneously with the Acquisition, all the outstanding Notes were redeemed. Healthy Hearts did not have sufficient cash on hand before the Acquisition to redeem the Notes.

Additional Facts:

The Acquisition meets the definition of a business combination.


• The terms of the Notes did not require Healthy Hearts to redeem or offer to
repurchase the Notes upon a change in control (i.e., the decision to redeem the
Notes was voluntary).


• It was Cool Care’s decision to redeem the Notes.


• The fair value of the Notes as of the date of the Acquisition was equal to the
amount paid to redeem the tendered Notes. In addition, Healthy Hearts carried the
Notes at their par value (i.e., there is neither a premium nor a discount present
with the Notes).

Required:


In consideration of the information presented above, draft a memo answering the following questions. Reference the FASB Accounting Standards in answer.

1. Should Healthy Hearts include the extinguishment of debt (i.e., the Notes) in its pre-combination financial statements or should Cool Care include it in its post-combination financial statements? Depending on the answer, determine the gain or loss on the extinguishment of debt to be recognized. (Note that for this question, the pre-combination financial statements represent Healthy Hearts’ operations before the Acquisition and the post-combination financial statements represent Cool Care’s consolidated financial statements after the Acquisition.)

2. Are there differences between ASC 805 and IFRS 3 that should be considered in

Designing a Simple Processor “X” using HDL

The encoding of an instruction set architecture (ISA) for a 16-bit processor can vary depending
on the specific design of the processor, but I can provide a general example of how instructions
might be encoded in such an ISA.
Assuming a simple 16-bit processor with a RISC-like design, the encoding of each instruction
could consist of a fixed-length 16-bit instruction word divided into fields, such as:
Opcode field: specifies the operation to be performed, such as add, subtract, load, store, etc.
This field could be 4 bits wide, allowing for up to 16 different operations.
Source register field: specifies the register containing the first operand. This field could be 3 bits
wide, allowing for up to 8 different registers.
Destination register field: specifies the register where the result will be stored. This field could
also be 3 bits wide.
Immediate field: specifies an immediate value to be used as the second operand in certain
instructions. This field could be 6 bits wide, allowing for immediate values in the range of -32 to
31.
Address field: specifies the memory address to be accessed in load and store instructions. This
field could be 7 bits wide, allowing for memory addresses in the range of 0 to 127.
Overall, the encoding of each instruction could look something like this:
Opcode (4 bits) Src Reg (3 bits)Dest Reg (3 bits) Immediate (6 bits) Address (7
bits)
This is just an example, and actual ISAs for 16-bit processors could differ in their encoding and
instruction format based on the specific requirements and design of the processor.
some additional details on the encoding of a simple 16-bit ISA.
Opcode Field: The opcode field specifies the operation to be performed by the instruction. In a
simple ISA, this field would typically be 4 bits wide, allowing for up to 16 different operations.
Some common operations might include:
Add/Subtract: These instructions add or subtract the value in the source register from the value
in the destination register, and store the result in the destination register.
Load/Store: These instructions read from or write to memory, using the address specified in the
address field as the memory location.
Jump/Branch: These instructions modify the program counter (PC) to jump to a new instruction
address or to branch to a different part of the program.
Source and Destination Register Fields: The source register field and destination register field
each specify a 3-bit register number. In a simple ISA, there might be 8 registers available,
numbered 0 through 7. The source register field specifies the register containing the first
operand, and the destination register field specifies the register where the result will be stored.
Immediate Field: The immediate field is used to provide an immediate value as the second
operand for certain instructions. For example, an add instruction might use the value in the
source register as one operand, and the value specified in the immediate field as the second
operand. In a simple ISA, the immediate field might be 6 bits wide, allowing for immediate
values in the range of -32 to 31.
Address Field: The address field is used to specify the memory address for load and store
instructions. In a simple ISA, the address field might be 7 bits wide, allowing for memory
addresses in the range of 0 to 127. Some ISAs might also have special addressing modes, such as
indexed addressing or indirect addressing, which use a combination of the address field and
other fields in the instruction to calculate the actual memory address to be accessed.
Overall, the encoding of an ISA for a 16-bit processor would be designed to balance the need for
a compact instruction format with the need to provide enough flexibility and functionality to
support a wide range of programs and applications. The specific encoding used would depend
on the design goals and requirements of the processor, as well as any constraints imposed by
the available hardware or software tools.
Let’s consider an example where our 16-bit ISA supports the following operations:
Add (ADD): adds the value in the source register to the value in the destination register and
stores the result in the destination register
Subtract (SUB): subtracts the value in the source register from the value in the destination
register and stores the result in the destination register
Load (LD): loads a value from memory into a register
Store (ST): stores a value from a register into memory
Branch if equal (BEQ): branches to a specified address if the values in two registers are equal
Jump (JMP): jumps to a specified address
No operation (NOP): does nothing
Here are some possible encodings for these instructions:

You can add more instructions if you

want

 

introduction to statistical programming with R course

General Guidelines
Please use R Markdown for your submission. Include the following files:
• Your .Rmd file.
• The compiled/knitted HTML document.
Name your .Rmd file with the convention 123456789_stats20_hw0.Rmd, where 123456789 is replaced with
your UID and hw0 is updated to the actual homework number. Include your first and last name and UID in
your exam as well. When you knit to HTML, the HTML file will inherit the same naming convention.
The knitted document should be clear, well-formatted, and contain all relevant R code, output, and
explanations. R code style should follow the Tidyverse style guide: https://style.tidyverse.org/.
Any and all course material, including these homework questions, may not be posted online or
shared with anyone at any time without explicit written permission by the instructor (Michael
Tsiang), even after the quarter is over. Failure to comply is a breach of academic integrity.
Note: All questions on this homework should be done using only functions or syntax discussed
in Chapters 1–2 of the lecture notes or Homeworks 1–2. No credit will be given for use of
outside functions.
Basic Questions
Collaboration on basic questions must adhere to Level 0 collaboration described in the Stats
20 Collaboration Policy.
The following code is used in Questions 1 and 2.
Consider the following code:
mixed1 <- c(TRUE, FALSE, FALSE, TRUE, 4, 0, 3)
mixed1
[1] 1 0 0 1 4 0 3
mixed2 <- c(TRUE, FALSE, FALSE, TRUE, 4, 0, “3”)
mixed2
[1] “TRUE” “FALSE” “FALSE” “TRUE” “4” “0” “3”
mixed3 <- c(c(TRUE, FALSE, FALSE, TRUE, 4, 0), “3”)
mixed3
[1] “1” “0” “0” “1” “4” “0” “3”
1
Question 1
The objective of this question is to help further your understanding of the mode hierarchy and the order in
which commands are evaluated.
(a)
Explain why mixed2 and mixed3 produce different results.
(b)
Use the same input values of TRUE, FALSE, FALSE, TRUE, 4, 0, “3” with the c() function to create the
following vector:
[1] “TRUE” “FALSE” “0” “1” “4” “0” “3”
Question 2
The objective of this question is to introduce the concept of type casting.
Type Casting: The as.logical(), as.numeric(), and as.character() functions allow us to coerce (or
cast) a vector into one of a different mode.
For example:
as.logical(c(“TRUE”, “FALSE”, “TRUE”))
[1] TRUE FALSE TRUE
as.numeric(c(“4”, “0”, “3”))
[1] 4 0 3
as.character(c(TRUE, FALSE, TRUE))
[1] “TRUE” “FALSE” “TRUE”
(a)
Run the commands as.numeric(mixed2) and as.numeric(mixed3) and explain why they produce different
results.
(b)
Run the commands as.logical(mixed2) and as.logical(mixed3) and explain why they produce different
results.
(c)
Use type casting functions to coerce mixed3 into a meaningful logical vector (i.e., with no NA values).
2
Question 3
The objective of this question is to give practice with the seq() and rep() functions and understand their
use and limitations.
Note: For all parts of this problem, sequences should be written in such a way that they would be generalizable
if the desired pattern was longer. For example, c(1, 2, 3, 4, 5) should be written as seq(1, 5), and
c(1, 1, 1, 1, 1) should be written as rep(1, 5). Extending these patterns to 1000 values would be
prohibitively cumbersome without using seq(1, 1000) and rep(1, 1000).
(a)
Generate the following sequence in four ways: using (i) the seq() function, (ii) the colon : operator,
(iii) the seq_len() function, and (iv) the seq_along() function.
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
(b)
Using seq() and rep() as needed, create the following vectors in R.
(i)
[1] 8.0 7.5 7.0 6.5 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0
(ii)
[1] -1 0 3 5 -1 0 3 5 -1 0 3 5 -1 0 3 5 -1 0 3 5
(iii)
[1] 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1
(iv)
[1] 5 5 5 5 5 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1
(v)
[1] 10 9 9 8 8 8 7 7 7 7 6 6 6 6 6
(c)
Explain why the following sequence cannot be generated using only the seq() and rep() functions in the
same way as the sequences in (b). What makes this pattern different from the patterns in (b)? How can you
generate this sequence?
[1] 10 9 8 7 6 9 8 7 6 5 8 7 6 5 4 7 6 5 4 3 6 5 4 3 2
Hint: Since this sequence cannot be generated using only seq() and rep(), consider another operation in
addition to seq() and rep() to combine simpler sequences into this more complicated pattern. You are
not allowed to use c() in your solution for this question.
Question 4
R has built-in trigonometric functions, such as sin(), cos(), tan(), asin(), acos(), and atan(). The
sin() function computes the sine of any numeric input.
Using at most two lines of code, compute sin(kπ), for k = 0, 1, 2, . . . , 100. Explain your result. Does the
output match what you would expect mathematically?
3
Question 5
The objective of this question is to give practice with vectorized operations and writing functions using
vectors.
The coefficient of skewness measures how much the distribution of a sample differs from symmetry. A
perfectly symmetric distribution will have a skewness of 0. If the skewness coefficient is significantly greater
than 0, then the distribution is right-skewed. If the skewness coefficient is significantly less than 0, then the
distribution is left-skewed.
The skewness coefficient for a sample of values x1, x2, . . . , xn is defined as
skew =

n
Pn
i=1
(xi − x¯)
3
Pn
i=1
(xi − x¯)
2
3/2
,
where x¯ =
1
n
Pn
i=1
xi
is the sample mean.
(a)
Write a function called my_skew() that computes the skewness for any numeric input vector x.
(b)
Use your my_skew() function to compute the skewness of Chris Traeger’s running times from the lecture
notes. Interpret your answer.
running_times <- c(51, 40, 57, 34, 47, 50, 50, 56, 41, 38)
(c)
Through algebraic manipulation, a one-pass formula for the coefficient of skewness is
skew =

n
Pn
i=1
x
3
i − 3¯x
Pn
i=1
x
2
i + 2nx¯
3

Pn
i=1
x
2
i − nx¯
2
3/2
.
Write a function called my_skew_one() that computes the skewness for any numeric input vector x using the
one-pass formula. Verify that your new function gives the same answer as your function from (a).
(d)
Multiply the running times by 1010 (1e10) and compute the skewness on the new vector using both of
your skewness functions. Do your results differ from your answers in (b) and (c)? Explain intuitively or
mathematically why or why not.
(e)
Even though the skewness of Chris Traeger’s running times should appear to be the same value in (b) and
(c), you likely will find the following (or similar) result when considering the difference in the values:
my_skew(running_times) – my_skew_one(running_times)
[1] -4.157785e-14
Explain why the difference is not identically 0.
4
Intermediate Questions
Collaboration on intermediate questions must adhere to Level 1 collaboration described in the
Stats 20 Collaboration Policy.
Several exercises throughout this course will ask you to code your own version of basic built-in functions from
scratch. While you will likely not need to rewrite existing functions from scratch when using R in practice,
the thought process of thinking through and writing these functions allows you to build your skills in breaking
down complicated problems into simpler steps and more deeply understanding the fundamental toolkit you
are building throughout the course.
A general strategy for how to think through writing functions from scratch:
1. Come up with small general examples and think about what your function ideally should do for those
examples. Do you notice patterns or using similar logic for every example?
2. Formalize and generalize the logic you used in your small examples to the general case. How should
your function work on the intended input argument(s) in general? Outline or describe the steps your
function needs to do to output the desired result.
3. Consider any edge cases, i.e., valid inputs that your function is supposed to work on but may not use
the same logic as the general case to work. See if the logic you used in general extends to the edge case.
If not, think about whether the general case can be modified to accommodate the edge case.
In Chapter 4, we will consider a flow control statement (an if or if-else statement) that allows
you to use/write entirely separate logic for different cases.
Question 6
(a)
Write a function called my_length() that computes the number of elements of a vector without the length()
function. The output of my_length(x) and length(x) should be identical for any vector x. Your function
must work for vectors of any mode and vectors of length 0.
(b)
Test your my_length() function from (a) with the following inputs:
(i) numeric(0)
(ii) seq(1, 99, by = 2)
(iii) c(“waffles”, “friends”, “work”)
Question 7
(a)
Write a function called my_rev() that reverses the order of elements in a vector without the rev() function.
The output of my_rev(x) and rev(x) should be identical for any vector x. Your function must work for
vectors of length 0.
(b)
Test your my_rev() function from (a) with the following inputs:
(i) numeric(0)
(ii) seq(1, 99, by = 2)
(iii) c(“waffles”, “friends”, “work”)
5
Question 8
(a)
Write a function called front() that inputs a vector x and a number n and outputs the first n elements of x.
When n is greater than length(x), your function should just output x.
With n = 6, verify that your front() function works on the vectors numeric(0), seq(1, 99, by = 2), and
c(“waffles”, “friends”, “work”). Also verify with n = 0 that your front() function works on one of
the aforementioned vectors.
(b)
Write a function called back() that inputs a vector x and a number n and outputs the last n elements of x.
When n is greater than length(x), your function should just output x.
With n = 6, verify that your back() function works on the vectors numeric(0), seq(1, 99, by = 2), and
c(“waffles”, “friends”, “work”). Also verify with n = 0 that your back() function works on one of the
aforementioned vectors.
(c)
Read through the following pseudocode:
FUNCTION: insert_at()
INPUTS: x, the vector the values are to be added to.
values, the values to be included in the modified vector.
at, the starting index of the inserted values.
OUTPUT: a vector with values inserted into vector x at the specified position.
beginning <- subset of `x` values with indices less than `at`
ending <- subset of `x` values with indices greater-than or equal to `at`
new_vec <- combination of beginning, values, and ending
OUTPUT: new_vec
Use your front() and/or back() functions from (a) and (b) to write a function called insert_at() that
inserts elements in a vector.
(d)
Verify that your insert_at() function works by executing the following commands:
insert_at(1:5, c(0, 0, 0), at = 1)
[1] 0 0 0 1 2 3 4 5
insert_at(1:5, c(0, 0, 0), at = 3)
[1] 1 2 0 0 0 3 4 5
insert_at(1:5, c(0, 0, 0), at = 5)
[1] 1 2 3 4 0 0 0 5
insert_at(1:5, c(0, 0, 0), at = 6)
[1] 1 2 3 4 5 0 0 0

COMP 120 ‐ Problem Solving Assignment 4

In this assignment you will attempt to find out your way out of a linked list labyrinth,
armed only with your wits and a debugger. Good Luck!
IMPORTANT: For this assignment you will be working by yourself.
Before you start coding, make sure you read through this whole document. If any of the
instructions aren’t clear, feel free to ask about it on CampusWire (use the PSA4 category).
Pre‐requisites
• Textbook1 Chapter 5
• Lab Sessions 08 (Debugging with VS Code)
Learning Objectives
Upon successful completion of this PSA you will be able to do the following.
• Use a debugger to examine the contents of memory
• Write Python code that uses the assert statement to check preconditions.
• Write Python code that raises an exception.
Initial Setup
Both you and your partner will need to get the starter code for your group using Git.
1. In VS Code, open the command palette and select the “Git Clone” option.
2. When prompted for the repository URL, enter the following, with X replaced by your
group number (e.g. 7 or 12).
ssh://git@code.sandiego.edu/comp120‐sp23‐s03‐psa4‐groupX
3. When prompted for where to save the repository, select the “comp120” folder you
created earlier this semester. If you happen to get an error, make sure you click the
“Git Log” button when prompted and look for the reported error message. Look at
CampusWire to see if anyone else got the same error message: if not, create a new
post, copying and pasting the output of the Git log.
4. Choose the “Open Repository” option in the window that pops up in the lower‐right
corner of the screen. In this repository you will find several Python files (*.py) and
several text files in a directory named data_files.
Note that when working on the PSA, you should be careful to only work on one computer at
a time (either you or your partner’s). If you want to switch between computers, make sure
you “Sync” your code.
IMPORTANT: As you complete and sync each problem, you can check the SAFE webapp for
the results of some limited testing. Note that the messages you receive from the tests run
are purposely vague: you should be relying on your own tests (as specified throughout
this assignment) to get the diagnostic feedback that you need to solve your problems.
Think of SAFE as a minimum backup to make sure that the very basics are working.
Computational Problem: Linked List Labyrinth
You have been trapped in a labyrinth, and your only hope to escape is to cast the magic
spell that will free you from its walls. To do so, you will need to explore the labyrinth to find
three magical items:
• The Spellbook (????), which contains the spell you need to cast to escape.
• The Potion (⚗), containing the arcane compounds that power the spell.
• The Wand (⚚), which concentrates your focus to make the spell work.
Once you have all three items, you can cast the spell to escape to safety.
This is, of course, no ordinary maze. It’s a reference maze. The maze consists of a collection
of objects of type MazeCell, where MazeCell is defined here:
class MazeCell:
whatsHere: Item # Item present, if any.
north: Optional[‘MazeCell’] # The cell north of us (if one exists)
south: Optional[‘MazeCell’]
east: Optional[‘MazeCell’]
west: Optional[‘MazeCell’]
Here, Item is this enumerated type:
class Item(Enum):
NOTHING
POTION
SPELLBOOK
WAND
For example, the following figure show a 4 × 4 labyrinth.
4×4 Labyrinth
We’ve marked your starting position with a smiley face and the positions of of the three
items with similarly cute emojis. The MazeCell you begin at would have its north, south,
east, and west pointers pointing at the MazeCell objects located one step in each of those
directions from you. On the other hand, the MazeCell containing the book would have its
north, east, and west pointers set to nullptr, and only its south pointer would point
somewhere (specifically, to the cell in the bottom‐left corner).
Each MazeCell has a variable named whatsHere that indicates what item, if any, is at that
position. Empty cells will have whatsHere set to the Item.NOTHING. The cells containing
the Spellbook, Potion, or Wand will have those fields set to Item.SPELLBOOK, Item.POTION,
or Item.WAND, respectively.
If you were to find yourself in this labyrinth, you could walk around a bit to find the items
you need to cast the escape spell. There are many paths you can take; here’s three of them:
1. ESNWWNNEWSSESWWN
2. SWWNSEENWNNEWSSEES
3. WNNEWSSESWWNSEENES
Each path is represented as a sequence of letters (N for north, W for west, etc.) that, when
fol‐lowed from left to right, trace out the directions you’d follow. For example, the first
sequence represents going east, then south (getting the Potion), then north, then west, etc.
Trace though those paths and make sure you see how they pick up all three items.
Milestone 1: Check Paths to Freedom
Your first task is to write a function that, given a cell in a maze and a path, checks whether
that path is legal and picks up all three items. Specifically, in the file main.py, implement the
function:
is_path_to_freedom(start_location: MazeCell, path: str) ‐> bool
This function takes as input your starting location in the maze and a string made purely
from the characters ‘N’, ‘S’, ‘E’, and ‘W’, then returns whether that path lets you escape from
the maze.
A path lets you escape the maze if (1) the path is legal, in the sense that it never takes a step
that isn’t permitted in the current MazeCell, and (2) the path picks up the Spellbook, Wand,
and Potion. The order in which those items are picked up is irrelevant, and it’s okay if the
path continues onward after picking all the items up.
The start_location should not be not None: make sure you an add an assert to the top of
the function to check for this precondition.
The path string may have characters that are not valid (i.e. not N, S, E, or W). If it does, you
should raise a ValueError exception, including a message that indicates what the invalid
character was.
To summarize, here’s what you need to do.
1. Implement the is_path_to_freedom function in main.py.
2. Test your code thoroughly using the tests found in test_main.py.
To run the test, you should just be able to press the “Play” button in VS Code, or you
can do the following in the Terminal: python3 ‐m pytest test_main.py
If you’d like to add your own tests to this file you’re welcome to do so, though it’s
not required here.
Notes
Some notes on this problem:
1. Your code should work for a MazeCell from any possible maze, not just the one
shown above.
2. Although in the previous picture the maze was structured so that if there was a link
from one cell to another going north there would always be a link from the second
cell back to the first going south (and the same for east/west links), you should not
assume this is the case in this function. Then again, chances are you wouldn’t need
to assume this.
3. A path might visit the same location multiple times, including possibly visiting
locations with items in them multiple times.
4. You shouldn’t need to create any new MazeCell objects in the course of solving this
problem. After all, your job is to check a path in an existing maze, not to make a new
maze.
5. Feel free to implement this function either iteratively or recursively, whichever
seems best to you. You don’t need to worry about recursion depth issues here; we’ll
never run your code on anything large enough to cause a problem.
6. Your code should not modify the maze passed into the function. In particular, you
should not change which items appear where or where the links point.
7. An edge case you should handle: it is okay to find the three items and then continue
to walk around the maze. However, if the path both, (1) finds all three items, and (2)
tries making an illegal step, then your function should return False.
Milestone 2: Escape From your Personal Labyrinth
Your next task is to escape from a labyrinth that’s specifically constructed for you. The
starter code we’ve provided will use your name(s) to build you a personalized labyrinth. By
personalized, we mean “no one else in the course is going to have the exact same labyrinth
as you.” Your job is to figure out a path through that labyrinth that picks up all the three
items, allowing you to escape.
In the file main.py and you’ll see three ALL_CAPS variables. (By convention, ALL_CAPS
variables are meant to represent variables that should never be reassigned.) The first one,
YOUR_NAME, is a spot for your name. Right now, it’s marked with a TODO message. Edit this
string so that it contains your full name.
This first half of main generates a personalized labyrinth based on the YOUR_NAME
constant and returns a pointer to one of the cells in that maze. It then checks whether the
constant PATH_OUT_OF_MAZE a sequence that will let you escape from the maze. Right now,
PATH_OUT_OF_MAZE is a TODO message, so it’s not going to let you escape from the
labyrinth. You’ll need to edit this string with the escape sequence once you find it.
To come up with a path out of the labyrinth, use the debugger! Set a breakpoint at the
indicated line in the main function. Run the program in VS Code, making sure you select
“Debug Python File” instead of the default run mode (“Run Python File”). When you do, you
should see the variables window pop up, along with the contents of start_location, which
is the MazeCell where we’ve dropped you into the labyrinth. Clicking the “>” symbol next
to the variable name in the debugger window will let you read the contents of the
whatsHere field of start_location (it’ll be Item.NOTHING), as well as the four reference
leading out of the cell.
Depending on your maze, you may find yourself in a position where you can move in all
four cardinal directions, or you may find that you can only move in some of them. The
pointers in directions you can’t go are all equal to None. The pointers that indicate
directions you can go will all have dropdown arrows near them. Clicking one of these
arrows will show you the MazeCells reachable by moving in the indicated directions. You
can navigate the maze further by choosing one of those dropdown arrows, or you could
back up to the starting maze cell and explore in other directions. It’s really up to you!
Draw a lot of pictures. Grab a sheet of paper and map out the maze you’re in. There’s no
guarantee where you begin in the maze: you could be in the upper‐left corner, dead center,
etc. The items are scattered randomly, and you’ll need to seek them out. Once you’ve
mapped out the maze, construct an escape sequence and stash it in the constant
PATH_OUT_OF_MAZE, then see if you pass the first test. If so, fantastic! You’ve escaped! If not,
you have lots of options.
You could step through your is_path_to_freedom function to see if one of the letters you
entered isn’t what you intended and accidentally tries to move in an illegal direction. Or
perhaps the issue is that you misdrew your map and you’ve ended up somewhere without
all the items. It’s also easy to get your directions backwards when you have it mapped out
on paper so be careful about that! You could alternatively set the breakpoint at the test case
again and walk through things a second time, seeing whether the picture of the maze you
drew was incorrect.
To summarize, here’s what you need to do:
1. Edit the constant YOUR_NAME at the top of main.py with a string containing your
name. Don’t skip this step! If you forget to do this, you’ll be solving the “default
labyrinth”, which is the wrong one! (You unfortunately won’t get credit for solving
this incorrect labyrinth).
2. Set a breakpoint at the first indicated line in main.py and run the program in debug
mode to trigger the debugger.
3. Map out the maze on a sheet of paper and find where all the items are. Once you’re
done, stop the running program.
4. Find a path that picks up all three items and edit the constant PATH_OUT_OF_MAZE at
the top of main.py with that path. Run the test a second time with the debugger
turned off to confirm you’ve escaped.
Milestone 3: Escape from Your Personal Twisty Labyrinth
Now, let’s make things a bit more interesting. In the previous section, you escaped from a
labyrinth that nicely obeyed the laws of geometry. The locations you visited formed a nice
grid, any time you went north you could then go back south, etc.
In this section, we’re going to relax these constraints, and you’ll need to find your way out
of trickier mazes that look like the one shown to the right.
The figure below shows one of these strange new types of labyrinths.
Twisty Labyrinth
This maze is stranger than the previous one you explored. For example, you’ll notice that
these MazeCells are no longer in a nice rectangular grid where directions of motion
correspond to the natural cardinal directions. There’s a MazeCell here where moving north
and then north again will take you back where you started. In one spot, if you move west,
you have to move south to return to where you used to be. In that sense, the names “north,”
“south,” “east,” and “west” here no longer have any nice geometric meaning; they’re just the
names of four possible exits from one MazeCell into another.
The one guarantee you do have is that if you move from one MazeCell to a second, there
will always be a direct link from the second cell back to the first. It just might be along a
direction of travel that has no relation to any of the directions you’ve taken so far.
The second half of main contains code that generates a twisty labyrinth personalized with
the YOUR_NAME constant. As before, you’ll need to find a sequence of steps that will let you
collect the three items you need to escape.
In many regards, the way to complete this section is similar to the way to complete the
previous one. Set a breakpoint in the indicated spot and use the debugger to explore the
maze. Unlike the previous section, though, in this case you can’t rely on your intuition for
what the geometry of the maze will look like. For example, suppose your starting location
allows you to go north. You might find yourself in a cell where you can then move either
east or west. One of those directions will take you back where you started, but how would
you know which one?
This is where memory addresses come in. Internally, each object in Python has a memory
address associated with it. Memory addresses typically are written out in the form
0xsomething, where something is the address of the object. You can think of memory
addresses as sort of being like an “ID number” for an object: each object has a unique
address, with no two objects having the same address. When you pull up the debugger view
of a maze cell, you should see the MazeCell memory address listed with the object (e.g. it
will say “MazeCell object at 0xbadbeef”).
For example, suppose that you’re in a maze and your starting location has address
0x10c3fa10 (the actual number you see will vary based on your computer), and you can
move to the south (which ways you can go are personalized to you based on your name, so
you may have some other direction to move). If you expand out the dropdown for the south
pointer, you’ll find yourself at some other MazeCell. One of the links out of that cell takes
you back where you’ve started, and it’ll be labeled 0x10c3fa10. Moving in that direction
might not be productive–it just takes you back where you came from–so you’d probably
want to explore other directions to search the maze.
It’s going to be hard to escape from your maze unless you draw lots of pictures to map out
your surroundings. To trace out the maze that you’ll be exploring, we recommend
diagramming it on a sheet of paper as follows. For each MazeCell, draw a circle labeled
with the memory address, or, at least the last five characters of that memory address.
(Usually, that’s sufficient to identify which object you’re looking at). As you explore, add
arrows between those circles labeled with which direction those arrows correspond to.
What you have should look like the picture above, except that each circle will be annotated
with a memory address. It’ll take some time and patience, but with not too much effort you
should be able to scout out the full maze. Then, as before, find an escape sequence from the
maze! To recap, here’s what you need to do:
1. Set a breakpoint at the indicated line in main and run the program in debug mode to
trigger the debugger.
2. Map out the twisty maze on a sheet of paper and find where all the items are and
how the cells link to each other. Once you’re done, stop the running program.
3. Find an escape sequence, and edit the constant PATH_OUT_OF_TWISTY_MAZE at the
top of main.py with that constant. Run the tests again–this time without the
breakpoint–and see if you’ve managed to escape!
Notes on this Milestone
Some notes on this milestone:
1. The memory addresses of objects are not guaranteed to be consistent across runs of
the program. This means that if you map out your maze, stop the running program,
and then start the program back up again, you are not guaranteed that the addresses
of the MazeCells in the maze will be the same. The shape of the maze is guaranteed
to be the same, though. If you do close your program and then need to explore the
maze again, you may need to relabel your circles as you go, but you won’t be
drawing a different set of circles or changing where the arrows link.
2. You are guaranteed that if you follow a link from one MazeCell to another, there will
al‐ways be a link from that second MazeCell back to the first, though the particular
directions of those links might be completely arbitrary. That is, you’ll never get
“trapped” somewhere where you can move one direction but not back where you
started.
3. Attention to detail is key here: different MazeCell objects will always have different
addresses, but those addresses might be really similar to one another. Make sure
that as you’re drawing out your diagram of the maze, you don’t include duplicate
copies of the same MazeCell.
4. The maze you’re exploring might contain loops or cases where there are multiple
distinct paths between different locations. Keep this in mind as you’re exploring or
you might find yourself going in circles!
5. Remember that you don’t necessarily need to map out the whole maze. You only
need to explore enough of it to find the three items and form a path that picks all of
them up.
Final Words
At this point, you have a solid command of how to use the debugger to analyze linked
structures. You know how to recognize memory addresses, how to manually follow links
between objects, and how to reconstruct the full shape of the linked structure even when
there’s bizarre and unpredictable cross‐links between them. We hope you find these skills
useful as you continue to write code that works on linked lists and other linked structures!
Grading
You will receive the following points for completing each of the three milestones.
• Milestone 1: Correctly implemented is_path_to_freedom <#pts 5>
• Milestone 2: Correct value for PATH_OUT_OF_MAZE with YOUR_NAME set to your name.
<#pts 5>
• Milestone 3: Correct value for PATH_OUT_OF_TWISTY_MAZE with YOUR_NAME set to
your name. <#pts 8>

Powered by WordPress