Answer:
#include <iostream>
#include <climits>
#include<fstream>
using namespace std;
int main ()
{
fstream filein;
ofstream fileout;
string inputfilename, outputfilename;
// ASk user to enter filenames of input and output file
cout<<"Enter file input name: ";
cin>>inputfilename;
cout<<"Enter file output name: ";
cin>>outputfilename;
// Open both file
filein.open(inputfilename);
fileout.open(outputfilename);
// Check if file exists [Output file will automatically be created if not exists]
if(!filein)
{
cout<<"File cannot be opened"<<endl;
return 0;
}
int min = INT_MAX;
int max = INT_MIN; //(Can't use 0 or any other value in case input file has negative numbers)
int count = 0; // To keep track of number of integers read from file
double average = 0;
int number;
// Read number from file
while(filein>>number)
{
// If min > number, set min = number
if (min>number)
{
min = number;
}
// If max < number. set max = number
if(max<number)
{
max = number;
}
// add number to average
average = average+number;
// add 1 to count
count+=1;
// If count reaches 10, break the loop
if(count==10)
{
break;
}
}
// Calculate average
average = average/count;
// Write result in output file
fileout<<"Max: "<<max<<"\nMin: "<<min<<"\nAverage: "<<average;
// Close both files
filein.close();
fileout.close();
return 0;
}
It is possible to force the Hardware Simulator to load a built-in version of chip Xxx. This can be done by: Select one: a. making sure the Xxx.hdl file is not loctaed in the current directory. b. leaving the chip body in the Xxx.hdl file empty. c. stating in the chip header that this is a built-in chip. d. once the chip was implemented by the user, this is not possible.
Answer:
C. Stating in the chip header that this is a built-in chip
Explanation:
The header of an HDL program is as follow:
CHIP chip name
{
IN input pin name
//statements
}
The simulator is using the following logic:
If Xxl.hdl exists
then load it into the simulator
else if Xxl.hdl exists in the built-in chip
then load it into the simulator and chip header
else
display "error message"
Answer:
c. stating in the chip header that this is a built-in chip.
Explanation:
The header of an HDL program is as follows;
CHIP chip name
{
IN input pin name
// statements
}
Syntax:
The stimulator is using the following logic
If Xxx.hdl exists
then load it into the stimulator
else if Xxx.hdl exists in the built-in chips
then load it into the stimulator and the chip header
else
display "error message"
*STATING IN THE CHIP HEADER THAT THIS IS A BUILT-IN CHIP
Challenge: Tic-Tac-Toe (Report a problem) Detecting mouse clicks For this step of the challenge you will complete Tile's handleMouseClick method. The handleMouseClick method has two parameters: x and y which represent the coordinates of where the user clicked the mouse. When a user clicks inside a tile, that tile's handleMouseClick method should call that tile's onClick method. To check if the mouse click is inside of the tile, you will need an if statement that checks if: - the mouse click is on, or right of, the left edge of the tile - the mouse click is on, or left of, the right edge of the tile - the mouse click is on, or below, the upper edge of the tile - the mouse click is on, or above, the lower edge of the tile
To detect a mouse click within a tile in a Tic-Tac-Toe game, one must implement a conditional statement in the handleMouseClick method that checks if the click's coordinates fall within the tile's bounds. If the click is valid, the tile's onClick method is called.
Explanation:The student's question concerns a programming task involving the development of a Tic-Tac-Toe game and specifically addresses the implementation of a method to detect mouse clicks within a tile. To accomplish this, the handleMouseClick method needs an if statement to check whether the click occurred within the boundaries of the tile. The if statement must compare the x and y coordinates of the mouse click against the left, right, upper, and lower edges of the tile.
To implement this, the conditional check might look like this:
if (x >= tileLeftEdge && x <= tileRightEdge && y >= tileTopEdge && y <= tileBottomEdge) {This code snippet checks that the mouse click's x coordinate is within the horizontal bounds of the tile and the y coordinate is within the vertical bounds. If both conditions are satisfied, it then calls the onClick method associated with the tile, indicating a valid click.
g (Locate the largest element) Write the following method that returns the location of the largest element in a two-dimensional array: public static int [] locateLargest(double [][] a) The return value is a one-dimensional array that contains two elements. These two elements indicate the row and column indices of the largest element in the two-dimensional array. Write a test program (the main method) that prompts the user to enter a two-dimensional array and displays the location of the largest element of the array.
Answer:
The method in JAVA is shown below.
static double largest = 0.0;
static int[] idx = new int[2];
public static int r = 20;
public static int c = 20;
public static int[] locateLargest(double[][] a)
{
for(int j=0; j<c; j++)
{
for(int k=0; k<r; k++)
{
if(largest<a[j][k])
{
largest=a[j][k];
idx[0]=k;
idx[1]=j;
}
}
}
return idx;
}
The JAVA program is shown below.
import java.util.Scanner;
import java.lang.*;
class program
{
//static variables declared and initialized as required
static double largest = 0.0;
static int[] idx = new int[2];
public static int r = 20;
public static int c = 20;
public static int[] locateLargest(double[][] a)
{
for(int j=0; j<c; j++)
{
for(int k=0; k<r; k++)
{
if(largest<a[j][k])
{
largest=a[j][k];
idx[0]=k;
idx[1]=j;
}
}
}
return idx;
}
}
public class Main
{
static double[][] arr;
static double input;
public static void main(String[] args){
program ob = new program();
arr = new double[ob.r][ob.c];
Scanner sc = new Scanner(System.in);
for(int j=0; j<ob.c; j++)
{
for(int k=0; k<ob.r; k++)
{
arr[j][k]=0;
}
}
System.out.println("Enter the elements of two dimensional array ");
for(int j=0; j<ob.c; j++)
{
for(int k=0; k<ob.r; k++)
{
input = sc.nextDouble();
if(input>0)
{ arr[j][k] = input;
//System.out.println(arr[j][k]);
}
else
break;
}
break;
}
int[] large_idx = ob.locateLargest(arr);
int row = large_idx[0];
int col = large_idx[1];
double l = arr[col][row];
System.out.println("The largest element in the user entered array is " + l);
}
}
OUTPUT
Enter the elements of two dimensional array
1
2
3
4
5
6
7
8
9
0
The largest element in the user entered array is 9.0
Explanation:
1. The class program contains the locateLargest() method as mentioned in the question.
2. The public class Main contains the main() method.
3. User input for array is taken inside main().
4. This array is passed to the locateLargest() method.
5. This method returns the one dimensional array having row and column indices of the largest element in the array.
6. The indices are used to display the largest element in the main().
Similar to Wi-Fi, ____ is designed to provide Internet access to fixed locations (sometimes called hotzones), but the coverage is significantly larger. a. WinMax b. WiMAX c. EMax d. 802.11b
Similar to Wi-Fi, WiMAX is a kind of hotspot, is designed to provide Internet access to fixed locations (sometimes called hot zones), but the coverage is significantly larger. Thus, the correct option for this question is B.
What is Wi-Fi?Wi-Fi stands for Wireless fidelity. It may be characterized as a wireless technology that is significantly used in order to connect computers, tablets, smartphones, and other devices to the internet. It processes the radio signal sent from a wireless router to a nearby device, which translates the signal into data you can see and use.
According to the context of this question, hotspot also follows the same working principle in order to connect devices like computers, mobile phones, etc, to the internet.
But the problem is that it connects the devices over a short distance. While WiMAX has the capability to connect devices where the coverage is significantly larger.
Therefore, similar to Wi-Fi, WiMAX is a kind of hotspot, is designed to provide Internet access to fixed locations (sometimes called hot zones), but the coverage is significantly larger. Thus, the correct option for this question is B.
To learn more about Wi-Fi, refer to the link:
https://brainly.com/question/13267315
#SPJ5
Final answer:
WiMAX, also known as Worldwide Interoperability for Microwave Access, is designed to provide Internet connectivity over larger areas than Wi-Fi, and is standardized as IEEE 802.16. It uses microwave communications to provide broadband wireless access, especially useful in areas without traditional cable or DSL infrastructure.
Explanation:
Similar to Wi-Fi, which is a wireless local area network technology allowing devices to connect to the Internet, WiMAX (Worldwide Interoperability for Microwave Access) is designed to provide Internet access to fixed locations over much larger coverage areas, sometimes referred to as hotzones.
WiMAX is standardized as IEEE 802.16, providing broadband wireless access (BWA) and enabling the formation of connections over long distances. It is essentially used for providing last mile broadband wireless access and can be a cost-effective alternative to traditional cable or DSL methods. WiMAX has become a valuable technology especially in areas that lack the infrastructure for cable or DSL connections, providing the necessary Internet access using microwave communications.
Repeat Programming Project 5 but in addition ask the user if he or she is a. Sedentary b. Somewhat active (exercise occasionally) c. Active (exercise 3–4 days per week) d. Highly active (exercise every day) If the user answers "Sedentary," then increase the calculated BMR by 20 percent. If the user answers "Somewhat active," then increase the calculated BMR by 30 percent. If the user answers "Active," then increase the calculated BMR by 40 percent. Finally, if the user answers "Highly active," then increase the calculated BMR by 50 percent. Output the number of chocolate bars based on the new BMR value.
Answer:
Explanation:
//C++ program to calculate the number of chocolate bars to consume in order to maintain one's weight.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
float weight,height;
int age,choice;
char gender;
float bmr;
// inputs
cout<<"\n Enter weight(in pounds) : ";
cin>>weight;
cout<<"\n Enter height(in inches) : ";
cin>>height;
cout<<"\n Enter age(in years) : ";
cin>>age;
cout<<"\n Enter gender(M for male , F for female) : ";
cin>>gender;
cout<<"\n Are you :\n 1. Sedentary \n 2. Somewhat active(exercise occasionally)\n 3. Active(exercise 3-4 days per week)\n 4. Highly active(exercise everyday)? ";
cout<<"\n Choice(1-4) ";
cin>>choice;
//calculate bmr based on the gender
if(gender == 'm' || gender == 'M')
{
bmr = 66+(6.3*weight)+(12.9*height)-(6.8*age);
}else if(gender == 'f' || gender == 'F')
{
bmr = 655+(4.3*weight)+(4.7*height)-(4.7*age);
}
// update bmr based on how active the user is
if(choice ==1)
bmr = bmr + (20*bmr)/100;
else if(choice == 2)
bmr = bmr + (30*bmr)/100;
else if(choice ==3)
bmr = bmr + (40*bmr)/100;
else if(choice ==4)
bmr = bmr + (50*bmr)/100;
// output
cout<<"\n The number of chocolate bar that should be consumed = "<<ceil(bmr/230);
return 0;
}
//end of program
The task involves calculating the basal metabolic rate (BMR), adjusting it based on activity level (Sedentary, Somewhat active, Active, Highly active), and then determining the equivalent number of chocolate bars. It emphasizes the importance of considering one's activity level in determining caloric needs.
Explanation:The question involves modifying a programming project to calculate a person's basal metabolic rate (BMR) and then adjusting it based on their level of activity before determining the number of chocolate bars equivalent to the adjusted BMR value. The activity levels are described as Sedentary, Somewhat active, Active, and Highly active, with corresponding increases of 20%, 30%, 40%, and 50% to the calculated BMR respectively.
BMR calculation is critical because it measures how much energy the body needs to perform basic bodily functions such as maintaining temperature, cell production, and nutrient processing at rest. The BMR does not include the energy used during physical activity or digestion. Factors influencing BMR include age, gender, body weight, and muscle mass. Interestingly, lean body mass, which is more metabolically active than fat tissue, is a significant determinant of BMR. Therefore, individuals with more muscle mass have a higher BMR.
To calculate the adjusted BMR based on activity level, one would first calculate the standard BMR and then apply the relevant percentage increase. For example, a sedentary person's BMR would be increased by 20%. This adjusted BMR can then be used to calculate the number of chocolate bars, assuming a typical chocolate bar contains around 250 calories, by dividing the adjusted BMR by the calorie content of the chocolate bars.
A prime number is any integer greater than 1 that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is a method of finding prime numbers. It operates as follows: Create a primitive type Boolean array with all elements initialized to true. Array elements with prime indices will remain true. All other array elements will eventually be set to false. Starting with array index 2, determine whether a given element is true. If so, loop through the remainder of the array and set to false every element whose index is a multiple of the index for the element with value true. Then continue the process with the next element with value true. For array index 2, all elements beyond element 2 in the array that have indices which are multiples of 2 (indices 4, 6, 8, 10, etc.) will be set to false; for array index 3, all elements beyond element 3 in the array that have indices which are multiples of 3 (indices 6, 9, 12, 15, etc.) will be set to false; and so on. When this process completes, the array elements that are still true indicate that the index is a prime number. These indices can be displayed. Write an application that uses an array of 1000 elements to determine and display the prime numbers between 2 and 999. Ignore array elements 0 and 1.
Answer:
see explaination
Explanation:
public class test{
public static void main(String[] args){
boolean flag[] = new boolean[1000];
for(int i = 0; i < 1000; i++){
flag[i] = true;
}
for(int i = 2; i < 1000; i++){
if(flag[i] == true){
for(int j = i + 1; j < 1000; j++){
if(j % i == 0) flag[j] = false;
}
}
}
System.out.println("The prime numbers in the range 0 to 1000 are:");
for(int i = 2; i < 1000; i++){
if(flag[i] == true) System.out.print(i + " ");
}
}
}
Consider the Telnet example discussed in Slide 78 in Chapter 3. A few seconds after the user types the letter ‘C’, the user types the letter ‘R’. After typing the letter ‘R’, how many segments are sent, and what is put in the sequence number and acknowledgement fields of the segments?
Answer:
3 Segments,
First segment : seq = 43, ack=80
Second Segment : seq = 80, ack=44
Third Segment: seq = 44, ack=81
Explanation:
Three segments will be sent as soon as the user types the letter ‘C’ and the he waits for a few seconds to type the letter ‘R’.
In our Telnet example, 42 and 79 for the client and server were the starting sequence number. Since the letter 'R' is typed and the starting seq is 42 is incremented by 1 byte. Therefore the sequence number in the first segment is 43 and the acknowlegement number is 80.
The second segment is sent from the server to the client. It echoes back the letter ‘C’. 43 is put in the acknowledgment field and tells the client that it has successfully received everything up through byte 42 and is now waiting for bytes 43 onward. This second segment has the sequence number 79 which is incremented by 1 byte. Therefore the sequence number in the second segment is 80 and the acknowlegement number is 44.
The third segment is sent from the client to the server. Its acknowledges the data it has received from the server. It has 80 in the acknowledgment number field because the client has received the stream of bytes up through byte sequence number 79 and it is now waiting for bytes 80 onward. This is also incremented by 1 byte. Therefore the sequence number in the second segment is 44 and the acknowlegement number is 81.
Final answer:
In a Telnet session, each keystroke is sent as a separate segment. Therefore, typing 'R' after 'C' sends one segment with a sequence number incremented by one from the previous, and an acknowledgment number also increased by one to acknowledge receipt of the previously received segment.
Explanation:
When the user types the letter 'R' after typing 'C' in a Telnet session, generally a single segment is sent for each keystroke because Telnet operates in character mode. In this mode of operation, every character generates a pair of segments: one from the client to the server (the telnet command) and one from the server to the client (the acknowledgment).
The sequence number in the segment sent after typing 'R' would be incremented by one compared to the previous segment's sequence number because each character sent is considered one byte of data. Similarly, the acknowledgment number would be set to one more than the last received segment's sequence number, acknowledging the successful receipt of that segment.
If we assume the initial sequence number is 'X' for the first segment carrying the 'C' and the server acknowledges with 'Y', then for the 'R' segment, the sequence number would be 'X+1' and the acknowledgment field would have 'Y+1' if no other data was sent or received in the interim.
One author states that Web-based software is more likely to take advantage of social networking (Web 2.0) approaches such as wikis and blogs. If this is the case, can we expect more social networking capabilities in all future software? Aside from LinkedIn, how can social media be leveraged by CIT graduates?
Answer:
Yes
Explanation:
I will say Yes. There are very much limitless possible and future we can expect from social media and even more from social networking. Its capabilities from upcoming software in the future. Since the Internet is in its early days of growing and cloud computing being introduced there are way more possibilities in the future.
Social media can be duely applied by CIT (Computer Information Technologies) graduates. It can be used to improve them in their career and also will helps them connect professionally. Quora is one such platform which is not exactly like LinkedIn but pretty much serves the purpose.
Write the Python code to implement each step of the following algorithm. Your code should use descriptive variable names and perform all of the calculations necessary using the variables you define. You should not manually perform any calculation.
Answer:
# the number of pizza is initialised
# to 5
number_of_pizza = 5
# number of slice in each pizza
# is initialised to 8
slice_in_each_pizza = 8
# total number of pizza is calculated
total_number_of_slices = number_of_pizza * slice_in_each_pizza
# number of guest who respond yes
# is initialised to 10
number_of_guest_respond_yes = 10
# additional 3 guest is added to existing guest
number_of_guest_respond_yes += 3
# number of left over slice is gotten by using modulo arithmetic
number_of_left_over_slice = total_number_of_slices % number_of_guest_respond_yes
# the number of left over slice
# is printed which is 1
print(number_of_left_over_slice)
Explanation:
Missing Question Part: Use a variable to store the number of pizzas ordered as 5.
Assuming there are 8 slices in each pizza, use a variable to store the total number of slices calculated using the number of pizzas ordered.
Use another variable to store the number of guests who had responded YES as 10.
Three more people responded YES. Update the corresponding variable using an appropriate expression.
Based on the guest count, set up an expression to determine the number of left-over slices if the slices would be evenly distributed among the guests. Store the result of the expression in a variable.
The program is written in Python and it is well commented.
For each of the following cases, select the type of NoSQL DBMS that would fit best the needs of the situation. a. The database has to support a relatively complex hierarchical internal record structure that may vary for each record. b. The key requirement for the database is to access a specific record as quickly as possible without any concern regarding the internal structure of the record. c. The data are particularly well suitable to be organized as a network of associations between the data items. d. It is important that the DBMS provides quick access to each of the records by a key value, but, in addition, it has to also allow easy access to the components of each record.
Answer:
Check the explanation
Explanation:
(a) There will be a need for the database to support a comparatively complex and complicated hierarchical internal record structure that may vary for each record. Column store NoSQL DBMS
(b)The key requirements for the database are to access a specific record structure as quickly as possible without any concern regarding the internal structure of the record. Key value store NoSQL DBMS
(c) The data are specifically well suited to be organized as a network of connections amid the data items. Graph Base NoSQL DBMS
(d) It is essential that the DBMS offers quick access to each of the records by a key value, but, in addition, it has to also allow easy access to the components of each record. Document store NoSQL DBMS
You client has stipulated that open-source software is to be used. Is this a functional or non-functional requirement? How early in the life-cycle model can this requirement be handled? Explain your answer.
Answer:
In the beginning of the model
Explanation:
This is believed to be a non functional requirement because the non- functional type of requirement as platform restrictions, reliability and time of response. These requirements are meant to be handled during the beginning of the life cycle model because all planing and analysis should be centered around the fact that customers desires to adopt the open source model.
13. Question
What are two characteristics of a 5Ghz band wireless network?
Check all that apply.
Answer:
The two major characteristics of the 5GHZ are Fast speed and Short range.
Explanation:
The two major characteristics of the 5GHZ are Fast speed and Short range.
5GHz operates over a great number of unique channels. With the 5GHz, there is less overlap, which means less interference, and this makes it produce a better performance. The 5GHz is a better option as long as the device is close to the router/access point. Thus, it operates at shirt ranges.
The 5GHz band possesses the ability to cut through network disarray and interference to maximize network performance. It has more channels for communication, and usually, there are not as many competing devices on the 5GHz band. Thus, it has a very fast speed.
Write a program that inputs a non negative integer,separates the integer into its digits and prints them separated by tabs each.For example, if the user types in 42339, the program should print:42339
Answer:
tab = ""
number = int(input("Enter a nonnegative integer: "))
while number:
digit = number % 10
if len(str(number)) != 1:
tab += str(digit) + "\t"
else:
tab += str(digit)
number //= 10
print(tab[::-1])
Explanation:
* The code is in Python
- Initialize an empty string to hold the digits
- Ask the user for the input
Inside the loop:
- Get the digits of the number. If the length of the number is not 1 (If it is not the first digit), put a tab between the digits. Otherwise, just put the number (This will get the numbers from the last digit. If number is 123, it gets 3 first, then 2, then 1)
- Print the string in reverse order
The question is about writing a program to separate digits of a non-negative integer and print them with tabs in between. A Python example is provided as a sample solution, where the digits are printed using a loop and tab-separated.
Explanation:The question involves writing a program that takes a non-negative integer as input, separates the individual digits, and prints them separated by tabs. This is a typical programming exercise that can be solved using various programming languages such as Python, Java, or C++. Below is an example of how one might write a simple program in Python to achieve the desired output:
number = input("Enter a non-negative integer: ")This program prompts the user to enter a non-negative integer. It then iterates through each character in the input string (in this case, a number) and prints each digit followed by a tab space.
Create a program that includes a function called toUpperCamelCase that takes a string (consisting of lowercase words and spaces) and returns the string with all spaces removed. Moreover, the first letter of each word is to be forced to its corresponding uppercase. For example, given "hello world" as the input, the function should return "HelloWorld". The main function should prompt the user to input a string until the user types "Q". For each string input call the function with the string and display the result. (Hint: You may need to use the toupper function defined in the header file.)
Answer:
#include<iostream>
using namespace std;
//method to remove the spaces and convert the first character of each word to uppercase
string
toUpperCameICase (string str)
{
string result;
int i, j;
//loop will continue till end
for (i = 0, j = 0; str[i] != '\0'; i++)
{
if (i == 0) //condition to convert the first character into uppercase
{
if (str[i] >= 'a' && str[i] <= 'z') //condition for lowercase
str[i] = str[i] - 32; //convert to uppercase
}
if (str[i] == ' ') //condition for space
if (str[i + 1] >= 'a' && str[i + 1] <= 'z') //condition to check whether the character after space is lowercase or not
str[i + 1] = str[i + 1] - 32; //convert into uppercase
if (str[i] != ' ') //condition for non sppace character
{
result = result + str[i]; //append the non space character into string
}
}
//return the string
return (result);
}
//driver program
int main ()
{
string str;
char ch;
//infinite loop
while (1)
{
fflush (stdin);
//cout<< endl;
getline (cin, str); //read the string
//print the result
//cout<< endl << "Q";
// cin >> ch; //ask user to continue or not
ch = str[0];
if (ch == 'q' || ch == 'Q') //is user will enter Q then terminatethe loop
break;
cout << toUpperCameICase (str);
cout << endl;
}
return 0;
}
Al and Bill are arguing about the performance of their sorting algorithms. Al claims that his O(N log N)-time algorithm is always faster than Bill's O(N2)-time algo- rithm. To settle the issue, they implement and run the two algorithms on many randomly generated data sets. To Al's dismay, they find that if N 〈 1000 the O(N2)- time algorithm actually runs faster, and only when N 〉 1000 the 0(N logN)-time (10 pts.) one is better. Explain why the above scenario is possible
The observed performance difference is due to the constant factors and lower-order terms in the algorithms, affecting the actual running times for different input sizes.
The observed difference in performance between Al's O(N log N)-time algorithm and Bill's O(N^2)-time algorithm is due to the inherent nature of Big O notation.
While Big O provides an upper bound on an algorithm's growth rate as N approaches infinity, it neglects constant factors and lower-order terms, which are crucial for smaller input sizes.
Consequently, for N < 1000, Al's algorithm may have a higher constant factor or additional overhead, causing it to be slower than Bill's algorithm with O(N^2) complexity.
However, as N increases and surpasses 1000, the superior growth rate of Al's O(N log N) algorithm starts to dominate, making it faster than Bill's O(N^2) algorithm.
This discrepancy emphasizes the significance of considering constant factors and lower-order terms when evaluating algorithm performance in real-world scenarios.
Learn more about algorithms here:
https://brainly.com/question/33337820
#SPJ3
Final answer:
Al's O(N log N) sorting algorithm may run slower than Bill's O(N^2) algorithm for small data sets due to the practical influence of constant factors, lower-order terms, and the characteristics of specific programming languages that Big-O notation ignores. Al's algorithm outperforms Bill's only for larger N, where Big-O's highest-order term dominates the run-time.
Explanation:
The scenario where Al's O(N log N)-time sorting algorithm is outperformed by Bill's O(N2)-time algorithm for N < 1000 can be explained by considering the constants and lower-order terms involved in algorithm performance, which are not captured by Big-O notation. Big-O provides an abstract overview of complexity, focusing on the highest-order term, and it tends to ignore constants and lower-order terms. However, these neglected elements can significantly impact the actual run-time in practice, especially for smaller sizes of N.
Moreover, programming languages' execution speeds and overheads for various operations can differ, which might result in a less efficient algorithm (in terms of Big-O) running faster in practice due to language-specific optimizations or lower constant factors. For instance, a simple O(N2) algorithm like bubble sort might have less overhead than a more complex O(N log N) algorithm and can execute faster for small data sets.
Only when data sets grow large enough does the complexity described by Big-O notation become the dominating factor, and Al's algorithm starts to outperform Bill's. It's a classic illustration of why algorithm analysis must consider both theoretical performance and practical implementation details such as constant factors and the characteristics of specific data sets.
1. Write a telephone lookup program. Read a data set of 1, 000 names and telephone numbers from a file that contains the numbers in random order. Handle lookups by name and also reverse lookups by phone number. Use a binary search for both lookups.
Answer:
Kindly note that, you're to replace "at" with shift 2 as the brainly text editor can't take the symbol
Explanation:
PhoneLookup.java
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class PhoneLookup
{
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the phonebook file: ");
String fileName = in.nextLine();
LookupTable table = new LookupTable();
FileReader reader = new FileReader(fileName);
table.read(new Scanner(reader));
boolean more = true;
while (more)
{
System.out.println("Lookup N)ame, P)hone number, Q)uit?");
String cmd = in.nextLine();
if (cmd.equalsIgnoreCase("Q"))
more = false;
else if (cmd.equalsIgnoreCase("N"))
{
System.out.println("Enter name:");
String n = in.nextLine();
System.out.println("Phone number: " + table.lookup(n));
}
else if (cmd.equalsIgnoreCase("P"))
{
System.out.println("Enter phone number:");
String n = in.nextLine();
System.out.println("Name: " + table.reverseLookup(n));
}
}
}
}
LookupTable.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
A table for lookups and reverse lookups
*/
public class LookupTable
{
private ArrayList<Item> people;
/**
Constructs a LookupTable object.
*/
public LookupTable()
{
people = new ArrayList<Item>();
}
/**
Reads key/value pairs.
"at"param in the scanner for reading the input
*/
public void read(Scanner in)
{
while(in.hasNext()){
String name = in.nextLine();
String number = in.nextLine();
people.add(new Item(name, number));
}
}
/**
Looks up an item in the table.
"at"param k the key to find
"at"return the value with the given key, or null if no
such item was found.
*/
public String lookup(String k)
{
String output = null;
for(Item item: people){
if(k.equals(item.getName())){
output = item.getNumber();
}
}
return output;
}
/**
Looks up an item in the table.
"at"param v the value to find
"at"return the key with the given value, or null if no
such item was found.
*/
public String reverseLookup(String v)
{
String output = null;
for(Item item: people){
if(v.equals(item.getNumber())){
output = item.getName();
}
}
return output;
}
}
Item.java
public class Item {
private String name, number;
public Item(String aName, String aNumber){
name = aName;
number = aNumber;
}
public String getName(){
return name;
}
public String getNumber(){
return number;
}
}
input.txt
Abbott, Amy
408-924-1669
Abeyta, Ric
408-924-2185
Abrams, Arthur
408-924-6120
Abriam-Yago, Kathy
408-924-3159
Accardo, Dan
408-924-2236
Acevedo, Elvira
408-924-5200
Acevedo, Gloria
408-924-6556
Achtenhagen, Stephen
408-924-3522
Kindly check the attached output image below.
(3 points) Write a program to process two large chunks of data (e.g., a large 3D array and an array of self-defined structures with each structure at least 256 Bytes) respectively. The array elements can be random. The process can be incrementing every element by 1 or others. Try different ways (e.g., stride-k reference, the loop orders or others) to traverse the array elements and simulate the program performance (i.e., running time). Note that you should record the time just before and after the data processing program, not including the data generation or other initiation programs. And you should calculate an average time of at least 5 experiments for each program.
Answer:
Check the explanation
Explanation:
#include <iostream> #include <chrono> using namespace std::chrono; using namespace std; struct X{ int a,b,c,d,e,f,g,h; }; int main(){ // 3D Array of integers 1000 x 1000 x 1000 int data1[10][10][10]; //Array of struct X struct X data2[10000] ; auto start = high_resolution_clock::now(); //stride 1 access data 1 Loop order 1: for(int i=0;i<1000;i++){ for(int j=0;j<1000;j++){ for(int k=0;k<1000;k++){ data1[i][j][k]; } } } auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 1 Loop Order 1"<<duration.count()<<endl; start = high_resolution_clock::now(); //stride 2 access data 1 Loop order 1: for(int i=0;i<1000;i+=2){ for(int j=0;j<1000;j+=2){ for(int k=0;k<1000;k+=2){ data1[i][j][k]; } } } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 2 Loop Order 1"<<duration.count()<<endl; start = high_resolution_clock::now(); //stride 1 access data 1 Loop order 2: for(int i=0;i<1000;i++){ for(int j=0;j<1000;j++){ for(int k=0;k<1000;k++){ data1[j][i][k]; } } } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 1 Loop Order 2"<<duration.count()<<endl; start = high_resolution_clock::now(); for(int i=0;i<10000;i++){ data2[i]; } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"Struct Array "<<duration.count()<<endl; }
Some Observations on the order:
Stride 1 goes over all the elements of the array Hence takes more time than stride 2 which goes over alternate elements.
Loop order in the row major form takes leads time than column major form!
Struct array takes no time to execute because the structs are not being accessed.
Check the code screenshot and code output in the attached image below.
Answer:
See explaination
Explanation:
#include <iostream> #include <chrono> using namespace std::chrono; using namespace std; struct X{ int a,b,c,d,e,f,g,h; }; int main(){ // 3D Array of integers 1000 x 1000 x 1000 int data1[10][10][10]; //Array of struct X struct X data2[10000] ; auto start = high_resolution_clock::now(); //stride 1 access data 1 Loop order 1: for(int i=0;i<1000;i++){ for(int j=0;j<1000;j++){ for(int k=0;k<1000;k++){ data1[i][j][k]; } } } auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 1 Loop Order 1"<<duration.count()<<endl; start = high_resolution_clock::now(); //stride 2 access data 1 Loop order 1: for(int i=0;i<1000;i+=2){ for(int j=0;j<1000;j+=2){ for(int k=0;k<1000;k+=2){ data1[i][j][k]; } } } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 2 Loop Order 1"<<duration.count()<<endl; start = high_resolution_clock::now(); //stride 1 access data 1 Loop order 2: for(int i=0;i<1000;i++){ for(int j=0;j<1000;j++){ for(int k=0;k<1000;k++){ data1[j][i][k]; } } } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"3D array Stride 1 Loop Order 2"<<duration.count()<<endl; start = high_resolution_clock::now(); for(int i=0;i<10000;i++){ data2[i]; } stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout<<"Struct Array "<<duration.count()<<endl; }
Kindly check attachment for screenshot of the source code for proper indentation.
A Personal Fitness Tracker is a wearable device that tracks your physical activity, calories burned, heart rate, sleeping patterns, and so on. One common physical activity that most of these devices track is the number of steps you take each day. If you have downloaded this book's source code from the Computer Science Portal, you will find a file named steps.txt in the Chapter 06 folder. (The Computer Science Portal can be found at www.pearsonhighered.com/gaddis.) The steps.txt file contains the number of steps a person has taken each day for a year. There are 365 lines in the file, and each line contains the number of steps taken during a day. (The first line is the number of steps taken on January 1st, the second line is the number of steps taken on January 2nd, and so forth.) Write a program that reads the file, then displays the average number of steps taken for each month. (The data is from a year that was not a leap year, so February has 28 days.)
Answer:
See explaination for the program code.
Explanation:
fh = open('steps.txt', 'r')
lines = fh.readlines()
start = 0
days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
print('{:<7s} {:<10s}'.format('Month', 'Average Steps'))
for m in range(12):
end = start + days_in_months[m]
steps = lines[start:end]
avg = 0
for s in steps:
avg = avg + int(s)
avg = avg // len(steps)
print('{:<7d} {:<10d}'.format(m+1, avg))
start = start + days_in_months[m]
Please kindly check attachment for for the program code.
In this exercise we have to use the knowledge of computational language in python to write the code.
This code can be found in the attached image.
To make it simpler the code is described as:
fh = open('steps.txt', 'r')
lines = fh.readlines()
start = 0
days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
print('{:<7s} {:<10s}'.format('Month', 'Average Steps'))
for m in range(12):
end = start + days_in_months[m]
steps = lines[start:end]
avg = 0
for s in steps:
avg = avg + int(s)
avg = avg // len(steps)
print('{:<7d} {:<10d}'.format(m+1, avg))
start = start + days_in_months[m]
See more about python at brainly.com/question/22841107
A Grocery store has 184 shelves for bottled goods. Each shelf can hold 27 bottles. How many bottles will the shelves hold in all.
Answer:
4,968
Explanation:
You just have to multiply
Express the worst case run time of these pseudo-code functions as summations. You do not need to simplify the summations. a) function(A[1...n] a linked-list of n integers) for int i from 1 to n find and remove the minimum integer in A endfor endfunction
Answer:
The answer is "O(n2)"
Explanation:
The worst case is the method that requires so many steps if possible with compiled code sized n. It means the case is also the feature, that achieves an average amount of steps in n component entry information.
In the given code, The total of n integers lists is O(n), which is used in finding complexity. Therefore, O(n)+O(n-1)+ .... +O(1)=O(n2) will also be a general complexity throughout the search and deletion of n minimum elements from the list.Write a function that takes as input an English sentence (a string) and prints the total number of vowels and the total number of consonants in the sentence. The function returns nothing. Note that the sentence could have special characters like dots, dashes, and so on.
Answer:
public static void vowelCount(String word){
int vowelCount =0;
int consonantCount =0;
int wordLen = word.length();
//a,e,i,o,u
for(int i=0; i<word.length(); i++){
if(word.charAt(i)=='a'||word.charAt(i)=='e'||word.charAt(i)=='i'
||word.charAt(i)=='o'||word.charAt(i)=='u'){
vowelCount++;
}
}
System.out.println("Number of Vowels: "+vowelCount);
System.out.println("Number of Consonants: "+ (wordLen-vowelCount));
}
Explanation:
The method vowelCount is implemented in Java
Receives a string as argument
Uses a for loop to iterate the entire string
Uses an if statement to check for vowels
Substract total vowels from the length of the string to get the consonants
See complete code with a main method below:
import java.util.Scanner;
public class num2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String word = in.nextLine();
//Removing all special characters and whitespaces
String cleanWord = word.replaceAll("[^a-zA-Z0-9]", "");
//Calling the Method
vowelCount(cleanWord);
}
//The method
public static void vowelCount(String word){
int vowelCount =0;
int consonantCount =0;
int wordLen = word.length();
//a,e,i,o,u
for(int i=0; i<word.length(); i++){
if(word.charAt(i)=='a'||word.charAt(i)=='e'||word.charAt(i)=='i'
||word.charAt(i)=='o'||word.charAt(i)=='u'){
vowelCount++;
}
}
System.out.println("Number of Vowels: "+vowelCount);
System.out.println("Number of Consonants: "+ (wordLen-vowelCount));
}
}
To count the number of vowels and consonants in an English sentence, you could write a function that iterates through each character in the string, checks whether it is a vowel or a consonant, and updates a count for each. Vowels are a, e, i, o, and sometimes u and y. The function disregards any non-alphabetic characters and returns nothing.
To write this function in Python, for example, you could create a list of vowels, iterate through each letter in the input string, and increment the corresponding count if the letter is a vowel or consonant. Python's str.isalpha() method can determine if a character is a letter, thus ignoring special characters and whitespaces. Note that the function should handle both uppercase and lowercase letters since English is case-insensitive while counting vowels and consonants. This function not only serves a practical coding challenge, but it also incorporates an understanding of the English language and its phonetic components.
5.11 Of these two types of programs:a. I/O-boundb. CPU-boundwhich is more likely to have voluntary context switches, and which is more likely to have nonvoluntary context switches? Explain your answer
Answer:
The answer is "both voluntary and non-voluntary context switch".
Explanation:
The description to this question can be described as follows:
Whenever processing requires resource for participant contextual switch, it is used if it is more in the situation of I/O tied. In which semi-voluntary background change can be used when time slice ends or even when processes of greater priority enter.
In option a, It requires voluntary context switches in I /O bound.In option b, it requires a non-voluntary context switch for CPU bound.Write a recursive method called repeat that accepts a string s and an integer n as parameters and that returns s concatenated together n times. For example, repeat("hello", 3) returns "hellohellohello", and repeat("ok", 1) returns "ok", and repeat("bye", 0) returns "". String concatenation is an expensive operation, so for an added challenge try to solve this problem while performing fewer than n concatenations.
Answer:
public static String repeat(String text, int repeatCount) {
if(repeatCount < 0) {
throw new IllegalArgumentException("repeat count should be either 0 or a positive value");
}
if(repeatCount == 0) {
return "";
} else {
return text + repeat(text, repeatCount-1);
}
}
Explanation:
Here repeatCount is an int value.
at first we will check if repeatCount is non negative number and if it is code will throw exception.
If the value is 0 then we will return ""
If the value is >0 then recursive function is called again untill the repeatCount value is 0.
The recursive method called repeat in this exercise will be implemented using the Kotlin programming language
fun repeat (s:String, n: Int ) {
repeat(n) {
println("s")
}
}
In the above code, the Kotlin repeat inline function was used to archive the multiple output of the desired string, here is a documentation of how the repeat keyword/function works inline
fun repeat(times: Int, action: (Int) -> Unit)
//Executes the given function action specified number of times.
Learn more about Recursive methods:
https://brainly.com/question/11316313
You wish to lift a 12,000 lb stone by a vertical distance of 15 ft. Unfortunately, you can only generate a maximum pushing force of 2,000 lb.
a. What is the amount of work you must input in order to move the stone?
b. What is the actual mechanical advantage (AMA) required by a machine to complete the work above?
c. You build a ramp to create the ideal mechanical advantage. What is the length of the ramp in feet?
Answer:
The answer is "180,000, 6, and 90"
Explanation:
The answer to this question can be described as follows:
[tex]\ force = 12,000 \ lb \\\\\ distance = 15 \ ft \\\\ \ Formula : \\\\ \ total \ work = force \times distance \\\\ \ IMA = \frac{load}{effort} \\\\\ OR \\\\ \ IMA = \frac{\ distance \ move \ by \ load }{\ distance \ moved \ by \ efforts}[/tex]
[tex]a ) \\\\\ total \ work = 12,000 \times 15 \\\\\ total \ work = 180,000 ft \cdot lbf[/tex]
[tex]b) \\\\IMA = \frac{12000}{2000} = 6 \\\\ c) \\\\IMA = \frac{Y}{15} \\\\6= \frac{Y}{15}\\\\Y= 90\\\\X = \sqrt{8100-225}\\\\X = \sqrt{90^2-15^2} \\\\X= \sqrt{7875} \\\\X =88.74 ft\\\\[/tex]
by comparing the length of the ramp is 90 ft.
Write one DDL statement to add a new table Project into exam1. It contains the followingthree columns:-ProjNum of char(3) type, which is the primary key of Project.-Pname of varchar(30) type, which could be null. If it has a value, its first three characters must be 'UH2' or 'UB5'.-Budget of smallmoney type, which cannot be null and must have a minimum of $1,500.
Answer:
Check the explanation
Explanation:
When it comes to database management systems, a query is whichever command that is used in the retrieval of data from a table. In a Structured Query Language (SQL), generally queries are more or less always made by using the SELECT statement.
I have been trying to type it here but it's not working
so kindly check the code in the attached image below
Enlighten server and client network architecture. support your answer with diagrams and give an example of servers that your computer or mobile is connected currently
Server & Client Network Architecture:
The server-client network can be described as a network where a centralized server (host) provides services to many clients (users). The server is a powerful machine that can handle multiple clients.
There are various types of servers some of them are:
File serverDNS serverApplication serverWeb serverMail serverDatabase serverBenefits of server & client network:
Centralized and securedEnhanced speed and performanceCustomizationExample:
Take the example of hospital patient management system where a centralized server has a huge database and is running the application and many client computers are connected to this server where doctors enter the information about patients and this information is then stored in the server.
Assume that two computers are directly connected by a very short link with a bandwidth of 125 Mbps. One computer sends a packet of 1000 Bytes to the other computer. What’s the end-to-end delay (ignoring the propagation delay)?
Answer:
End to End Delay = 64 micro second
Explanation:
Given
Bandwidth = 125Mbps
A packet = 1000 bytes
Converting bandwidth from Mbps to bit/s
Bandwidth = 125* 10^6 bits/s
Bandwidth = 125,000,000 bit/s
End to End delay is calculated as
Length of Packet ÷ Bandwidth
Length of Packet = 1,000 byte --- convert to bits
Length of Packet = 1000 * 8
Length of Packet = 8,000 bits
So, End to End delay = 8,000/125,000,000
End to End Delay = 0.0000064 seconds --- convert to micro second
End to End Delay = 64 micro second
A router receives a packet and determines the outbound link for the packet. When the packet arrives, 2/3 of one other packet is done being transmitted on this outbound link and five other packets are waiting to be transmitted. Packets are transmitted in order of arrival. Suppose all packets are 3,000 bytes, and the link rate is 4 Mbps. What is the queuing delay for the packet
Answer:
Queuing Delay is 0.08 seconds
Explanation:
The answer follows a formula that is relatively easy to use and is detailed below.
Queuing Delay = [(L - x) + (nL)] / R
where,
L is packet length given as 3,000 bytes
x is the currently transmitted packet given as 2/3 * 3,000 = 2,000
n is the number of packets waiting in the Que given as 5
R is the rate of transmission given as 4 Mbps (4 * 10^6 Bps)
We can simply plug in the above information in the equation for computing Queuing Delay.
Lets take the numerator first which would be [(3000 - 2000) + (5 * 3000)]
The numerator would be 16000 bytes. These are being transmitted at 4Mbps. So, 16000*4*5 = 320,000 "bits"
Queuing Delay= 320,000/4000000
Queuing Delay = 0.08 seconds.
As we can see, the formula is quite intuitive to use. You are simply taking the number of packets to be transmitting, incorporating the partially transmitted packet, multiplying by the number of packets and the rate of transmission and then dividing the product by the rate of transmission to compute what the delay in the Que is.
In previous counters that you have created, you set the upper limit as the value just past the last digit you wanted displayed. That is not the case with this design. Why is how you set the range different for this design?
Answer:
The Synchronous load is synchronous and the Asynchronous load input is delayed with the counter pulse by one when it counts up.
Explanation:
The Synchronous load is synchronous and when it goes through the input load then the count from the Q outputs will stay the same. The Asynchromous load input is bit different and it delays the counters pulse by one when it counts up. it adds 1 to the pulse when it counts down. This means that it will either add or subtract 1 to the restart/maximum binary count.
Final answer:
The number of digits displayed in calculations holds significance for accuracy and precision.
Explanation:
When working with numbers, the number of **digits** you decide to display or consider is crucial. It is essential to be aware of the **accuracy**, **precision**, and **significant figures** in your calculations.
In terms of displayed values, setting the range differently in certain designs may be to highlight the **significance** of the last digit. This last digit often indicates the level of **error** in the calculation and is crucial for conveying the **precision** of the result. The question posed relates to the design of counters in engineering and why the range setting differs in the given design compared to previous ones. In engineering designs, especially those involving counters that detect voltage changes and display them, the precision of measurement and display is crucial. The decision on how to set the range, or the number of digits displayed, is influenced by the principles of accuracy, precision, and significant figures
Write your own unique Python program that has a runtime error. Do not copy the program from your textbook or the Internet. Provide the following.
The code of your program.
Output demonstrating the runtime error, including the error message.
An explanation of the error message.
An explanation of how to fix the error.
Answer:
myVariable = 3 print(myvariable)Runtime error:
NameError: name 'myvariable' is not defined
Explanation:
Runtime error is an error detected when running a program. In the given code example, there is a variable, myVariable initialized with 3 (Line 1). In the second line, we try to print the variable. But instead of placing myVariable in the print function, we put myvariable which is a different variable name (even though the difference is only with one lowercase letter). The Python will capture it as a runtime error as the variable name cannot be defined.
To fix the error, we just need to change the variable name in print statement to myVariable
myVariable = 3 print(myVariable)The runtime error inside a program is the one that happens when the program is being executed after it has been successfully compiled. It's also known as "bugs," which are frequently discovered during the debugging phase first before the software is released.
Code:
Demonstrating the output with a runtime error, including the error message.
a= input("input any value: ")#defining a variable that input value
b= int(input("Enter any number value: "))#defining b variable that input value
s=a+b#defining s variable that adds the inputs value
print(s)#print added value
In the above-given code, when "s" variable "adds" the input values it will give an error message, and to solve these errors we must convert the b variable value into the string, since "a" is a string type variable.
Correction in code:
#Code 1 for demonstrating the output with runtime error, including the error message.
a= input("input any value: ")#defining a variable that input value
b= int(input("Enter any number value: "))#defining b variable that input value
b=str(b)#defining b variable that converts input value into string and hold its value
s=a+b#defining s variable that adds the inputs value
print(s)#print added value
Output:
Please find the attached file.
Learn more:
brainly.com/question/21296934