The Drunkard’s (Random) Walk. Imagine you live on an infinite grid of streets where locations are represented as integer pairs (avenue,street). Negative numbers are okay in this example. Now consider a drunkard that randomly picks one of four directions at an intersection and then stumbles to the next intersection doing the same and so on. Write a class Drunkard to simulate this behavior given the drunkard’s initial position. Your Drunkard class should have as instance variables the drunkard’s current avenue (x location) and current street (y location). Your class should have a method called step( ) that moves the drunkard to the next randomly chosen adjacent intersection. Your class should have another method called fastForward(int steps) that takes an integer as a parameter (call it steps) and moves the drunkard steps intersections from his current location. Your class should have a method getLocation( ) that returns a String indicating the drunkard’s current location. Finally your class should have a method called howFar( ) that reports the drunkards distance in blocks from where he started calculated using the Manhattan distance metric.
You will find a test class called DrunkardTester below. Your Drunkard class must work with the test class provided without modification. You must NOT alter the test class.
DrunkardTester.java :
/**
* A tester for the Drunkard class.
*/
import java.util.Scanner;
public class DrunkardTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the starting
avenue integer: ");
int avenue = input.nextInt();
System.out.println("Please enter the starting street
integer: ");
int street = input.nextInt();
// make the Drunkard with initial position
Drunkard ozzy = new Drunkard(avenue,street);
// have him move 100 intersections
ozzy.fastForward(100);
// get his current location
String location = ozzy.getLocation();
// get distance from start
int distance = ozzy.howFar();
System.out.println("Current location: " +
location);
System.out.println("That's " + distance + " blocks
from start.");
}
}
Additionally, there is a completely empty Drunkard.java file that you must fill out.
(Your code goes here...)
Note that the definition of Manhattan distance is:
“The distance between two points in a grid based on a strictly horizontal and/or vertical path (that is, along the grid lines), as opposed to the diagonal or “as the crow flies” distance. The Manhattan distance is the simple sum of the horizontal and vertical components, whereas the diagonal distance might be computed by applying the Pythagorean theorem.”
In: Computer Science
Write a Python program that uses while loops to perform the following steps and post the text code. Thanks
a. Prompt the user to input two positive integers (no zero or
negative). variables: firstNum and
secondNum (firstNum must be less
than secondNum). Validate the user's input; prompt
the user again if firstNum is not less than
secondNum (use while loop).
b. Output all odd numbers between firstNum and
secondNum. (use while loop).
c. Output the sum of all even numbers between
firstNum and secondNum. (use
while loop).
d. Output the sum of the square of the odd numbers between
firstNum and secondNum. (use
while loop)
Program layout for each step:
#A
while loop
#B
while loop
#C
while loop
#D
while loop
***Allow the user to repeat the program. (requires another while loop).
***Do NOT define any functions.
***Your program output must be exactly the same as the output in the OUTPUT section, except font style.
OUTPUT:
- The bold text is the user's input.
*************************************************************************************
Enter two positive integer numbers.
First number must be less than the second number: Enter numbers: 8 a Incorrect Input. Please try again. Enter two positive integer numbers. First number must be less than the second number: Enter numbers:
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number: Enter numbers: a 8 Incorrect Input. Please try again. Enter two positive integer numbers. First number must be less than the second number: Enter numbers:
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number: Enter numbers: 8 2 First number must be less than the second number! Please try again. Enter two positive integer numbers. First number must be less than the second number: Enter numbers:
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number: Enter numbers: -2 8 No negative numbers! Please try again. Enter two positive integer numbers. First number must be less than the second number: Enter numbers:
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number you enter Enter numbers: 2 8 Odd integers between 2 and 8 are: 3 5 7 Sum of even integers between 2 and 8 = 20 Sum of the squares of odd integers between 2 and 8 = 83 Do you want to repeat this program? y/n > y
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number you enter Enter numbers: 1 9 Odd integers between 1 and 9 are: 1 3 5 7 9 Sum of even integers between 1 and 9 = 20 Sum of the squares of odd integers between 1 and 9 = 165 Do you want to repeat this program? y/n > y
*************************************************************************************
Enter two positive integer numbers. First number must be less than the second number you enter Enter numbers: 11 15 Odd integers between 11 and 15 are: 11 13 15 Sum of even integers between 11 and 15 = 26 Sum of the squares of odd integers between 11 and 15 = 515 Do you want to repeat this program? y/n > n Bye!
In: Computer Science
Can someone please fix my program? I keep getting a syntax error. Thanks (Python)
from tkinter import *
class LoanCalculator:
def __init__(self):
window = Tk()
window.title("Loan Calculator")
Label(window,text = "Annual Interest Rate").grid(row = 1, column
= 1, sticky = W)
Label(window,text = "Number of Years").grid(row = 2, column = 1,
sticky = W)
Label(window,text = "Loan Amount").grid(row = 3, column = 1, sticky
= W)
Label(window,text = "Monthly Payment").grid(row = 4, column = 1,
sticky = W)
Label(window,text = "Total Payment").grid(row = 5, column = 1,
sticky = W)
self.annualInterestRateVar = StingVar()
Entry(window,textvariable =
self.annualInterestRateVar,Justify=Right).grid(row = 1, column =
2)
self.numberofYearsvar = StringVar()
Entry(window,textvariable =
self.numberofYearsVar,Justify=Right).grid(row = 2, column =
2)
self.loanAmountVar = StringVar()
Entry(window,textvariable =
self.self.loanAmountVar,Justify=Right).grid(row = 3, column =
2)
self.monthlyPaymentVar = StringVar()
lblMonthlyPayment = Label(window,textvariable =
self.monthlyPaymentVar)\
.grid(row = 5, column = 2, Sticky = E)
self.totalPaymentVar = StringVar()
lblTotalPayment = Label(window,textvariable =
self.totalPaymentVar)\
.grid(row = 5, column = 2, Sticky = E)
btComputePayment = Button(window, text = "Compute Payment",
\
command = self.computePayment).grid(row = 6, column = 2, sticky =
E)
window.mainloop()
def computePayment(self):
try:
monthlyPayment =
self.getMonthlyPayment(float(self.loanAmountVar.get()),\
float(self.annualInterestRateVar.get())/1200,\
int(self.numberOfYearsVar.get())
self.monthlyPaymentVar.set('%.2f' % monthlyPayment)
totalPayment = float(self.monthlyPaymentVar.get())*12
*int(self.numberOfYearsVar.get())
self.totalPaymentVar.set('%.2f' % totalPayment)
except:
self.totalPaymentVar.set("Error in input")
def
getMonthlyPayment(self,loan,Amount,monthlyInterestRate,numberOfYears):
monthlyPayment = loanAmount * monthlyInterestRate/(1-1/ \
(1 + monthlyInterestRate)**(numberOfYears*12))
return monthlyPayment
def main():
LoanCalulator()
In: Computer Science
Consider a CSMA-like protocol with n nodes. Assume that the length of a time step equals twice the maximum propagation delay between any two nodes. Recall that if the medium is sensed busy, the node continuously monitors the medium until it becomes idle. When the medium becomes idle, the node sends the frame with probability p and defers it for a later slot with probability 1 − p. Assume that each node has an infinite number of frames to send, and that all frames are of the same size. Also, assume that each frame takes exactly one time step to be completely transmitted. Assume that when the medium experiences a collision during a current time step, it must stay idle during the next time step before it can proceed with transmission attempts again. But when the medium experiences a successful transmission during a current time step, nodes can immediately proceed with transmission attempts without needing to go idle for one time step. Also, assume that when a collision occurs during a time step, each node is able to detect it by the end of the time step during which the collision has occurred. Since the current state of the system depends only on its immediate past state, we can use Markov chains to model and analyze the performance of this system. For this, consider that the system has 3 states: idle i, colliding c, and transmitting t. All answers must be expressed in terms of p and n.
1. Draw the Markov state transition diagram and show the state transition probabilities?
2.Write the balance equation for each state, and derive the stationary probabilities for all states?
3.Derive the system throughput, defined as the average number of successfully delivered frames per time step?
4.Derive the system utilization, defined as the fraction of time the medium is being used for successful transmissions?
5.Drive the average waiting time, defined as the average time from when a frame is ready to be transmitted until the time the frame is transmitted successfully?
In: Computer Science
## Problem Description
You are writing a small section of an ATM machine where you accept a string that is a password and accept it or reject it. If the user tries more than three times with a bad password the card is blocked and no password will be accepted until the **resetFailedAttemptCounter** method is called. The password is provided at creation of the AtmPin. Security is a priority!
The class to implement this is referred to as **AtmPin** and consists of the following public methods:
**public AtmPin(String actualCode)** - Creates an AtmPin object with the provided code as the actual PIN
**public boolean verifyPinCode(String code)** - Accepts a string which represents the user's entry of their pin code. If the string matches the actual code provided in the constructor and the account is not blocked then the method returns true. Returns false when the code is bad OR when **isAccountLocked**() is true due to too many consecutive bad verification attempts. If an invalid code was passed or a valid code, but the account is blocked, the system will increment the number of bad password attempts.
**public boolean lastAttemptFailed()** - Returns true if the last invocation of **verifyPinCode** was unsuccessful. Underlying state is updated every time a password is passed to **verifyPinCode**. This method DOES NOT do the verification of the code, but simply is a record of whether the last attempt was successful. Note that you can submit a good password but have it rejected by the system since the account is locked (**verifyPinCode** returns false).
**public boolean isAccountLocked()** - If *more than* three consecutive attempts are made then the password is not accepted (**verifyPinCode** returns false) until **resetFailedAttemptCounter** is called.
**public void resetFailedAttemptCounter()** - Resets the number of failed attempts to zero.
Your **Program.java** should contain code to test your **AtmPin** object.
**Requirements:**
- You may not hard-code the pin in the AtmPin class, but must provide it as a constructor argument
- DO NOT STORE the user's code when attempting to verify
- **verifyPinCode** returns false when
- code is bad
- OR
- when **isAccountLocked**() is true due to too many consecutive bad verification attempts
- **lastAttempt** failed should not do any comparison of actual pin to the tested pin (i.e. you cannot store the user's pin)
## Getting Started
Create the following files in the folder and add the appropriately named classes to them
1. Program.java
2. AtmPin.java
In: Computer Science
SpeechAnalyst
The purpose of this assignment is to practice using strings and
C-strings. Your task is to create a class that counts words (by
looking for spaces) and sentences (by looking for periods). The
data will either come in dribs-and-drabs. Use the infamous operator
"<<" to output the data seen so far. Because
std::string is a class, I'd recommend you use it
to store the text information that has been entered through calls
to addData and addStringData.
|
Implementation Details |
Sample Driver |
|||
|
SpeechAnalyst sa; sa.clear(); |
|||
|
Sample Output |
||||
|
No data to print out.... |
HINT: You may add additional methods to the SpeechAnalyst class as long as you implement those defined in the original class definition.
In: Computer Science
Write a java program that takes 5 students final test scores from console when prompting. Store these scores in an array. Iterate thru the array of student scores to find –
Highest score entered
Lowest score entered
Average of all the 5 scores
Total of all the scores
Print these values to the console (screen).
In: Computer Science
Write a program that prompts the user to enter a date in the
format mm/dd/yyyy
where mm is the month , dd is the day and yyyy is a 4 digit
year
Check if the date is valid by seeing month is between 1 and 12, day
is between 1 to 31 and year is between 1800 to 3000. Also check
that if month is 2, day is between 1 to 29
If the date is valid then display the date back in following format
dd month year. Use of SimpleDateFormat Java Class is NOT allowed to
do this assignment. You need to use String functions from Chapter 4
to do this assignment.
Following is a sample run:
Enter a date in the format mm/dd/yyyy:
02/23/1999
23 Feb 1999
Following is another sample run:
Enter a date in the format mm/dd/yyyy:
02021999
Input String Length should be 10
Following is another sample run:
Enter a date in the format mm/dd/yyyy:
02-23-2000
Invalid Date Format
Following is another sample run:
Enter a date in the format mm/dd/yyyy:
23/02/2000
Invalid Date
In: Computer Science
1)
The provided file has syntax and/or logical errors. Determine the problem(s) and fix the program.
Grading
When you have completed your program, click the Submit button to record your score.
// Uses
DisplayWebAddress method three times
using static System.Console;
class DebugSeven1
{
static void Main()
{
DisplayWebAddress;
Writeline("Shop at Shopper's World");
DisplayWebAddress;
WriteLine("The best bargains from around the world");
DisplayWebAddres;
}
public void DisplayWebAddress()
{
WriteLine("------------------------------");
WriteLine("Visit us on the web at:");
WriteLine("www.shoppersworldbargains.com");
WriteLine("******************************");
}
}
2)
The provided file has syntax and/or logical errors. Determine the problem(s) and fix the program.
Grading
When you have completed your program, click the Submit button to record your score.
// Address an envelope
using names and addresses
// stored in two parallel arrays
using static System.Console;
class DebugSeven2
{
static void Main()
{
string[] addressees = {"Ms. Mary Mack", "Mr. Tom Thumb", "Dr.
Seuss"};
string[] addresses = {"123 Main", "456 Elm" "87 Maple"};
for(int x = 0; x < addressees.Length; ++x)
AddressEnvelope(addresses[x], addresses[x]);
}
private static void AddressEnvelope(string person, string
street)
{
WriteLine("To : {0}", person);
WriteLine(" {1}", street);
for(x = 0; x < 30; ++x)
Write("-");
WriteLine();
}
}
In: Computer Science
An engine operates with four essential variables controlling its operation. For the engine to be operating properly, at least two of its control variables must be present at the same time. However, when the machine is not operating correctly, we wish to have some signal to alert us to the problem. Design a circuit to implement the state when the alarm signal is present
In: Computer Science
c++ problem:
Implement a class money. You must have friend functions for I/O that overload << and >>. You must have multiple constructors, You must implement a percentage method,+,-, <,>. There is a starting money class in your text.
Example output:
Enter an amount of money: $14.33
Your amount is $14.33
My amount is $10.09
One of us is richer.
You have more money than me.
10% of your money is: $$1.43
$14.33 + $10.09 equals $24.42
$14.33 - $10.09 equals $4.24
Press any key to continue . . .
In: Computer Science
What (if anything) is wrong with the following code:
int redCount = 0, blueCount = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please make a selection: ");
String option = scan.next();
while(!option.startsWith("q") || !option.startsWith("Q"))
{
if(option.equals("red"))
{
redCount++;
}
else
{
blueCount++;
}
System.out.println("Please enter another value: ");
option = scan.next();
}
System.out.println("Red: " + redCount + ", Blue: " + blueCount);
|
The condition is not a boolean expression. |
||
|
A variable is out of scope. |
||
|
There is nothing wrong with this code. |
||
|
It will result in an infinte loop. |
||
|
It contains a logic error that will cause it to function incorrectly. |
What (if anything) is wrong with the following code:
int redCount = 0, int blueCount = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please make a selection: ");
String option = scan.next();
while(!option.toLowerCase().startsWith("q"))
{
if(option.equals("red"))
{
redCount += 1;
}
else
{
blueCount += 1;
}
System.out.println("Please enter another value: ");
option = scan.next();
}
System.out.println("Red: " + redCount + ", Blue: " + blueCount);
|
A variable is out of scope. |
||
|
The condition is not a boolean expression. |
||
|
It will result in an infinte loop. |
||
|
There is nothing wrong with this code. |
||
|
It contains a logic error that will cause it to function incorrectly. |
In: Computer Science
C language
· Pointers · Dynamic memory allocation · Functions · Arrays (dynamically allocated)
PROBLEM: The user of your program will use it to do some
elementary calculations for an unknown number of simple data sets.
The data in each set consists of a number of floating point values,
but the number of
the values to be entered will be input by the user, so you do not
know in advance how many values there will be in each data set.
Therefore, you cannot use a static array in C to
store these numbers, because a statically declared array has a
fixed size, which cannot be changed after the program begins
running.
First, you should prompt the user to enter the number of
data sets. The user will enter an integer greater than 1 to
indicate the number of data sets.
You should then prompt the user to enter the number of
floating point values in each data set (which the user will enter
as an integer greater than 0), followed by the floating point
values themselves on the same line (newline will follow
the last floating point value on the line). Your program needs to
read the user input, and store the floating point values in each
data set in a dynamically allocated array of the appropriate
size.
After getting the values in each data set, your program
should repeatedly do the following two things:
Select the data set to do operations on by number, with the
following prompt:
Enter the number of the data set on which you wish to do
calculations:
The user will enter an integer value, followed by newline, in
response to this prompt (the user will enter 1 for the first data
set, 2 for the second, etc.), and based on the value entered, your
program must be able to access the values in the appropriate data
set in the dynamically allocated storage which you have created,
and then do what is described immediately below.
Your program should then prompt the user to choose one of the
following options for a calculation based on the data set chosen by
the user (ask the user to enter one of the six numbers, followed by
enter):
1. Find the minimum value.
2. Find the maximum value.
3. Calculate the sum of all the values.
4. Calculate the average of all the values.
5. Print the values in the data set.
6. Exit the program.
After the user selects one of these six options, your program
should do the necessary calculation or printing of the data based
on the user's choice (or terminate the program), and output the
result with an appropriate message, for
example:
The maximum value in the data set is: 569.45
The results for options 1, 2, 3, and 4 should be printed out as
floating point values with 2 digits of precision, and the result
for option 5 should be to output the values in the data set in the
order in which they were input, with two digits of precision for
each value, and with any two values separated by a tab (\t).
Sample Data Set Input (This does not include user responses to
the prompts to select a data set or to select an operation to
perform)
6
3.45 2.37 85.32 34.5 569.45 335.2 193.4 74.39
6 23.45 32.37 185.32 364.5 179.4
144.39 7 35.45 121.47 42.32 44.5
249.75 385.9 113.4 4 44.45 567.37 311.32
22.45 2.37 85.32 34.5 569.45
335.2 193.4 74.39 122.45 413.2 89.32
2
1
3
2
4
3
5
4
6
5
6
In: Computer Science
Using the predicate symbols shown and appropriate quantifiers, write each English statement as a predicate wff. (The domain is the whole world.) (
A(x): x is an animal B(x): x is a bear H(x): x is hungry W(x): x is a wolf
a. Bears are animals.
b. Some animals are hungry bears.
c. No wolf is a bear.
In: Computer Science