Complete the function to replace any period by an exclamation point. Ex: "Hello. I'm Miley. Nice to meet you." becomes:


"Hello! I'm Miley! Nice to meet you!"

#include

#include

using namespace std;

void MakeSentenceExcited(char* sentenceText) {


/* Your solution goes here */

}


int main() {

const int TEST_STR_SIZE = 50;

char testStr[TEST_STR_SIZE];

strcpy(testStr, "Hello. I'm Miley. Nice to meet you.");

MakeSentenceExcited(testStr);


cout << testStr << endl;


return 0;


}

Answers

Answer 1

Answer:

Here is the complete function:

void MakeSentenceExcited(char* sentenceText) {  // function that takes the text as parameter and replaces any period by an exclamation point in that text

int size = strlen(sentenceText);  //returns the length of sentenceText string and assigns it to size variable

char * ptr;  // character type pointer ptr

ptr = sentenceText;  // ptr points to the sentenceText string

for (int i=0; i<size; i++){  //iterates through the sentenceText string using i as an index

    if (sentenceText[i]=='.'){  // if the character at i-th index of sentenceText is a period

        sentenceText[i]='!'; } } } //places exclamation mark when it finds a period at i-th index of sentenceText

Explanation:

The program works as follows:

Suppose we have the string:

sentenceText = "Hello. I'm Miley. Nice to meet you."

The MakeSentenceExcited method takes this sentenceText as parameter

int size = strlen(sentenceText) this returns the length of sentenceText

The size of sentenceText is 35 as this string contains 35 characters

size =  35

Then a pointer ptr is declared which is set to point to sentenceText

for (int i=0; i<size; i++) loop works as follows:    

1st iteration:

i=0

i<size is true because i=0 and size = 35 so 0<35

So the body of loop executes:

 if (sentenceText[i]=='.') statement checks :

if (sentenceText[0]=='.')

The first element of sentenceText is H

H is not a period sign so the statement inside if statement does not execute and value of i increments to 1. Now i = 1

2nd iteration:

i=1

i<size is true because i=1 and size = 35 so 1<35

So the body of loop executes:

 if (sentenceText[i]=='.') statement checks :

if (sentenceText[1]=='.')

This is the second element of sentenceText i.e. e

e is not a period sign so the statement inside if statement does not execute and value of i increments to 1. Now i = 2

So at each iteration the if condition checks if the character at i-th index of string sentenceText is a period.

Now lets see a case where the element at i-th index is a period:

6th iteration:

i=5

i<size is true because i=5 and size = 35 so 5<35

So the body of loop executes:

 if (sentenceText[i]=='.') statement checks :

if (sentenceText[5]=='.')

This is the character at 5th index of sentenceText i.e. "."

So the if condition evaluates to true and the statement inside if part executes:

sentenceText[i]='!'; statement becomes:

sentenceText[5]='!'; this means that the character at 5th position of sentenceText string is assigned an exclamation mark.

So from above 6 iterations the result is:

Hello!

This loop continues to execute until all the characters of sentenceText are checked and when the value of i gets greater than or equal to the length of sentenceText then the loop breaks.

The screenshot of the program along with its output is attached.

Complete The Function To Replace Any Period By An Exclamation Point. Ex: "Hello. I'm Miley. Nice To Meet

Related Questions

Why MUST you request your DSO signed I-20 ship as soon as it is ready and who is responsible to request the I-20

Answers

Why MUST you request your DSO signed I-20 ship as soon as it is ready and who is responsible to request the I-20?

a. It is required you have an endorsed/signed I-20 when Customs and Border Patrol or police ask for it

b. We only keep an unsigned digital copy and cannot sign an I-20 after the fact

c. It is against U.S. regulations to send digital (signed or not) DS-2019s and must treat I-20s the same

d. You will need all signed original I-20s to make copies to apply for OPT, STEM and H-1B in the future, so get them now!

e. It is the student’s choice to request each term, however, we cannot go back retroactively to provide past copies

f. We can only provide a signed copy of current I-20 and if changes occur from previous semesters that information will not show

g. The original endorsed I-20 signed by a DSO will be destroyed after 30 days of issuance if not picked up, and it cannot be replicated

h. The cost to have I-20 shipped may go up at any time

i. All the above

Answer:

i. All the above

Explanation:

DSO means designated school officials and they have to do with Student and Exchange Visitor Program (SEVP)-certified schools where students have to get a Form I-20, “Certificate of Eligibility for Nonimmigrant Student Status which provides information about the student's F or M status.

What a student must request for from his DSO signed I-20 ship are all the above options.

1a) Skills are increasingly the key variable of the entire process of access and information inequality in the information society. Discuss the 21st century competencies or skills required in the information society and four ways (4) you can apply it during Supported Teaching on Schools.​

Answers

Answer:

Explanation:

Skill acquisition improves quality, competence and competitiveness of an individual, It boost the chances of success and ability to make an impact. Access to information plays a verybhuge role in the society as it enables hearers to get updated while those who aren't informed are left behind. Some of the key competences or skills required in the information society include:

Critical thinking : Problem identification and ways to solve them.

Information sourcing and gathering : knowing where to get vital informations and facts

Effective communication, creativity, leadership, social, media and technological skills and so on.

The skills could be can be applied on schools in the form of :

Creating clubs such as the writing and debate clubs where students are given a research topic to write and present, this improves their research ability and communication skill.

Group project or assignment improves collaboration between members.

Assignments or projects requiring technology : Students may be given problems to solve with the use of computers moutwr programs and technology, this will help mad improve productivity.

Reward for innovation: Students should be paused mad encouraged for being creative, this will improve such individual and push others as well.

why is operating system pivotal in teaching and learning

Answers

Answer:

Kindly see explanation

Explanation: The operating system is a huge part of a computer system which plays a an invaluable role in the working of computer programs, hardwares and influences the overall experience of the user. It operating system serves as the interface between the computer hardware itself and the user who may wish to perform different tasks using a computer. In other to teach and learn, it is necessary to input and also obtain output, store our files and process and most essentially one may need to install application programs or softwares, all these functions are made possible with the help of an operating system. In essence, a system without an operating system can perform very little to no function at all. So basically teaching and learning becomes difficult. Teaching and Learning tools such as video, writing and other application softwares cannot be installed without an operating system and thus teaching or learning becomes impossible in it's absence.

In using cloud infrastructures, the client necessarily cedes control to the CP on a number of issues that may affect security
a. True
b. False

Answers

Answer:

A. True

Explanation:

The correct option is A. True.

Actually, in using cloud infrastructures, the client necessarily cedes control to the CP on a number of issues which may affect security. It may have to restrict port scans and even penetration testing. Moreover, the service level agreements may not actually guarantee commitment to offer such services on the part of the CP. This may result in leaving a gap in security defenses.

Also, when the control of the CP changes, it's evident that the terms and conditions of their services may also change which may affect security.

(Process scores in a text file) Suppose that a text file contains an unspecified number of scores. Write a program that reads the scores from the file and displays their total and average. Scores are separated by blanks. Your program should prompt the user to enter a filename. Here is a sample run:

Answers

Answer:

Here is the Python program:

def scores(file):  # method scores that takes a file name as parameter and returns the sum and average of scores in a file

   with open(file, 'r') as infile:  # open the file in read mode

       lines = [score.split() for score in infile]  # split the scores into a list

       print("The scores are:",lines)  #print the scores

       for line in lines:  # loops through each score

           total= sum(int(score) for score in line)  # adds the scores

           average =total/len(line) # computes average by taking sum of scores and dividing by number of scores in file

       print("The sum is:", total)  #prints the sum of scores

       print("The average is:", "{:.2f}".format(average))   #prints the average

filename = input("Enter name of the file: ")  #prompts user to enter name of file

scores(filename) #calls scores method by passing the file name to it in order to compute sum and average of file contents i.e. scores

Explanation:

It is assumed that the scores in the file are separated by a blank space.

The scores() method takes a file name as parameter. Then it opens that input file in read mode using object infile.

split() method is used to split the scores in a file into a list. Suppose the scores are 1 2 3 4 5 6 . So after the split, they become ['1', '2', '3', '4', '5', '6']  

The loop iterates through each score in the file, splits them into a list and stores this list in lines. The next print statement prints these scores in a list.

The second loop for line in lines iterates through each score of the list and the statements: total= sum(int(score) for score in line)  and average =total/len(line) computes the total and average of scores.

total= sum(int(score) for score in line)  statement works as follows:

for loop iterates through each element of list i.e. each score

int() converts that string element into integer.

sum() method adds the integers to compute their total.

So if we have  ['1', '2', '3', '4', '5', '6']  each element i.e. 1,2,3,4,5,6 is converted to integer by int() and then added together by sum method. So this becomes 1+2+3+4+5+6 = 21. This result is stored in total. Hence

total = 21.

average = total/len(line) works as follows:

The computed sum of scores stored in total is divided by the number of scores. The number of scores is computed by using len() method which returns the length of the line list. So len() returns 6. Hence

average = total/len(line)

              = 21 / 6

average = 3.5

The next two print statement prints the value of sum and average and "{:.2f}".format(average)) prints the value of average up to 2 decimal places.

The screenshot of the program along with its output is attached.

how do you run a function in python?

Answers

You can call a Python function like so: function(parameters).

Example:

Define function add:
def add(x,y):
return x+y

Call function:
add(3,7) -> 10

b. Does “refactoring” mean that you modify the entire design iteratively? If not, what does it mean?

Answers

Explanation:

Refactoring consists of improving the internal structure of an existing program's source code, while preserving its external behavior. 

Explain data hazard and structural hazard. Then, explain how we can prevent each type of hazard. Provide two examples to support your explanations

Answers

Answer:

Answered below

Explanation:

Data hazards happen when instructions exhibiting data dependence modify data in the different stages of a pipeline. Potential data hazards when not attended to, can result in race hazards or race conditions. Examples of situations where data hazards can occur is read after write, write after read, write after write. To resolve data hazards we can insert a pipeline whenever a read after write, dependence is encountered, use out-of-order execution or use operand forwarding.

Structural hazards happen when multiple instructions which are already in pipeline new the same resource. Example is a situation which many instructions are ready to execute an there is a single Arithmetic Logic Unit. Methods for preventing this hazard include pipeline break an pipeline flushing.

 A ………….. is a basic memory element in digital circuits and can be used to store 1 bit of information.

Answers

Answer:

A memory cell

Explanation: Research has proven that ;

The memory cell is also known as the  fundamental building block of computer memory.

It stores one bit of binary information and it must be set to store a logic 1 (high voltage level) and reset to store a logic 0 (low voltage level).

What are the constraints for designing small and large files and how these are resolved in different file system

Answers

Answer:

space management and buffering speed.

Explanation:

There are different types of file management systems in a computer system, examples of which are NTFS, FAT, WAFL, etc, and are governed by protocols like NFS, TFTP, FTP, etc.

These file systems are used in storages like the hard disk drive, CD and DVD, solid-state drive, etc, to organize or manage the files from boot setup, device drivers to permission-seasoned user files.

Files in storage range from small to large files, for which the schema of the file system must adjust to manage and allocate free space to other files in the future. The file system is also able to index the location of a file for retrieval to a cache memory, making buffering faster.

CHALLENGE 7.1.1: Initialize a list. ACTIVITY Initialize the list short.names with strings 'Gus', Bob, and 'Ann'. Sample output for the given program Gus Bob Ann 1 short_names- Your solution goes here 2 # print names 4 print(short_names[0]) 5 print(short names [11) 6 print(short_names[2])

Answers

Answer:

short_names = ["Gus", "Bob", "Ann"]

print(short_names[0])

print(short_names[1])

print(short_names[2])

Explanation:

There are some typos in your code. In addition to the missing part of the code, I corrected the typos.

First of all, initialize the list called short_names. The list starts with "[" and ends with "]". Between those, there are must be the names (Since each name is a string, they must be written between "" and there must be a semicolon between each name)

Then, you can print each name by writing the name of the list and the index of the names between brackets (Index implies the position of the element and it starts with 0)

Using virtualization comes with many advantages, one of them being performance. Which of these is NOT another realistic advantage of using virtualization over dedicated hardware?a. There are improvements in security and high availability during outage.b. There are cost benefits.c. Maintenance and updates are simplified or eliminated.d. There are fewer points of failure.

Answers

Answer:

a. There are improvements in security and high availability during outage

Explanation:

Virtualization occurs when data that could be in several formats (for example, storage devices) are made to appear real through a software. There are virtualization providers who act as third-party between users and the original manufacturers of the software. While virtualization has received wide popularity in recent times because of the several advantages it offers of which cost-saving is included, it also has some disadvantages. One of them from the options provided is the possibility of a security breach and its uncertain availability.

The security breach arises because of the proliferation of information on the virtual space. This information can be accessed by unauthorized hackers. Also since third-party providers are the usual providers of virtualization services, the availability depends on them because if they shut down, users can no longer access the software.

Consider the following Stack operations:

push(d), push(h), pop(), push(f), push(s), pop(), pop(), push(m).

Assume the stack is initially empty, what is the sequence of popped values, and what is the final state of the stack? (Identify which end is the top of the stack.)

Answers

Answer:

Sequence of popped values: h,s,f.

State of stack (from top to bottom): m, d

Explanation:

Assuming that stack is  initially empty. Suppose that p contains the popped values. The state of the stack is where the top and bottom are pointing to in the stack. The top of the stack is that end of the stack where the new value is entered and existing values is removed. The sequence works as following:

push(d) -> enters d to the Stack

Stack:  

d ->top

push(h) -> enters h to the Stack

Stack:

h ->top

d ->bottom

pop() -> removes h from the Stack:

Stack:

d ->top

p: Suppose p contains popped values so first popped value entered to p is h

p = h

push(f) -> enters f to the Stack

Stack:

f ->top

d ->bottom

push(s) -> enters s to the Stack

Stack:

s ->top

f

d ->bottom

pop() -> removes s from the Stack:

Stack:

f ->top

d -> bottom

p = h, s

pop() -> removes f from the Stack:

Stack:

d ->top

p = h, s, f

push(m) -> enters m to the Stack:

Stack:

m ->top

d ->bottom

So looking at p the sequence of popped values is:

h, s, f

the final state of the stack:

m, d

end that is the top of the stack:

m

Let PALINDROME_DFA= | M is a DFA, and for all s ∈ L(M), s is a palindrome}. Show that PALINDROME_DFA ∈ P by providing an algorithm for it that runs in polynomial time.

Answers

Answer:

Which sentence best matches the context of the word reticent as it is used in the following example?

We could talk about anything for hours. However, the moment I brought up dating, he was extremely reticent about his personal life.

Explanation:

Which sentence best matches the context of the word reticent as it is used in the following example?

We could talk about anything for hours. However, the moment I brought up dating, he was extremely reticent about his personal life.

Create a class named CarRental that contains fields that hold a renter's name, zip code, size of the car rented, daily rental fee, length of rental in days, and total rental fee. The class contains a constructor that requires all the rental data except the daily rate and total fee, which are calculated bades on the sice of the car; economy at $29.99 per day, midsize at 38.99$ per day, or full size at 43.50 per day. The class also includes a display() method that displays all the rental data. Create a subclass named LuxuryCarRental. This class sets the rental fee at $79.99 per day and prompts the user to respond to the option of including a chauffer at $200 more per day. Override the parent class display() method to include chauffer fee information. Write an application named UseCarRental that prompts the user for the data needed for a rental and creates an object of the correct type. Display the total rental fee. Save the files as CarRental.java, LuxaryCarRental.java, and UseCarRental.java.

Here is my code:

package CarRental;
public class CarRental
{
String name;
int zipcode;
String size;
double dFee;
int days;
double total;

public String getName()
{
return name;
}
public int getZipcode()
{
return zipcode;
}
public String getSize()
{
return size;
}
public int getDays()
{
return days;
}
public CarRental(String size)
{
if(size.charAt(0)=='m')
dFee = 38.99;
else
if(size.charAt(0)=='f')
dFee = 43.50;
else
dFee = 29.99;
}
public void calculateTotal(int days)
{
total = dFee*days;
}
public void print()
{
System.out.println("Your rental total cost is: $" + total);
}

}

package CarRental;
import java.util.*;
public class LuxaryCarRental extends CarRental
{
public LuxaryCarRental(String size, int days)
{
super(size);
}
public void CalculateTotalN()
{
super.calculateTotal(days);
dFee = 79.99;

int chauffer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Do you want to add a chauffer for $200? Enter 0 for"
+ " yes and 1 for no");
chauffer = keyboard.nextInt();

if(chauffer!=1)
total = dFee;
else
total = dFee + 100;
}
}

package CarRental;
import java.util.*;
public class UseCarRental
{
public static void main(String args[])
{
String name, size;
int zipcode, days;

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter total days you plan on renting: ");
days = keyboard.nextInt();

System.out.println("Enter your name: ");
name = keyboard.next();

System.out.println("Enter your billing zipcode: ");
zipcode = keyboard.nextInt();

System.out.println("Enter the size of the car: ");
size = keyboard.next();

CarRental economy = new CarRental(size);
economy.calculateTotal(days);
economy.print();

LuxaryCarRental fullsize = new LuxaryCarRental(size, days);
fullsize.CalculateTotalN();
fullsize.print();

}

Answers

Answer:

Here is the corrected code: The screenshot of the program along with its output is attached. The comments are written with each line of the program for better understanding of the code.

CarRental.java

public class CarRental  {  //class name

//below are the data members name, zipcode, size, dFee, days and total

String name;  

int zipcode;

String size;

double dFee;

int days;

double total;  

public String getName()  {  //accessor method to get the name

return name; }

public int getZipcode()  { //accessor method to get the zipcode

return zipcode; }

public String getSize() {  //accessor method to get the size

return size; }

public int getDays() {  //accessor method to get the days

return days;  }

public CarRental(String size)  {  //constructor of CarRental class

if(size.charAt(0)=='e')  // checks if the first element (at 0th index) of size data member is e

     dFee = 29.99;  // sets the dFee to 29.99

  else if(size.charAt(0)=='m')  // checks if the first element (at 0th index) of size data member is m

     dFee = 38.99;  // sets the dFee to 38.99

  else   // checks if the first element (at 0th index) of size data member is f

     dFee =43.50;  // sets the dFee to 43.50

   }

public void calculateTotal(int days) {  //method calculateTotal of CarRental

total = dFee*days;  }  //computes the rental fee

public void print()   {  //method to display the total rental fee

System.out.println("Your rental total cost is: $" + total);  } }

Explanation:

LuxuryCarRental.java

import java.util.*;

public class LuxuryCarRental extends CarRental {  //class LuxuryCarRental that is derived from class CarRental

public LuxuryCarRental(String size, int days) {  // constructor of LuxuryCarRental

super(size);}   //used when a LuxuryCarRental class and CarRental  class has same data members i.e. size

public void calculateTotal() {  //overridden method

super.calculateTotal(days); // used because CarRental  and LuxuryCarRental class have same named method i.e.  calculateTotal

dFee = 79.99;  //sets the rental fee at $79.99 per day

total = dFee;  }  //sets total to rental fee value

public void print(){  //overridden method

   int chauffeur;  // to decide to include chauffeur

Scanner keyboard = new Scanner(System.in);  //used to take input from user

System.out.println("Do you want to add a chauffeur for $200? Enter 0 for"

+ " yes and 1 for no");  // prompts the user to respond to the option of including a chauffeur at $200 more per day

chauffeur = keyboard.nextInt();   //reads the input option of chauffeur from user

if(chauffeur==1)  //if user enters 1 which means user does not want to add a chauffeur

total = dFee;  //then set the value of dFee i.e.  $79.99  to total

else  //if user enters 0 which means user wants to add a chauffeur

total = dFee + 200;  //adds 200 to dFee value and assign the resultant value to total variable

System.out.println("Your rental total cost is: $" + total);  }  } //display the total rental fee

UseCarRental.java

import java.util.*;

public class UseCarRental{ //class name

public static void main(String[] args){ //start of main() function body

String name, size; // declare variables

int zipcode, days; //declare variables

Scanner keyboard = new Scanner(System.in); // to take input from user

System.out.println("Enter total days you plan on renting: "); //prompts user to enter total days of rent

days = keyboard.nextInt(); // reads value of days from user

System.out.println("Enter your name: "); //prompts user to enter name

name = keyboard.next(); //reads input name from user

System.out.println("Enter your billing zipcode: "); // prompts user to enter zipcode

zipcode = keyboard.nextInt(); //reads input zipcode from user

System.out.println("Enter the size of the car: "); // prompts user to enter the value of size

size = keyboard.next(); //reads input size from user

CarRental economy = new CarRental(size); //creates an object i.e. economy of class CarRental

economy.calculateTotal(days); //calls calculateTotal method of CarRental using instance economy

economy.print(); //calls print() method of CarRental using instance economy

LuxuryCarRental fullsize = new LuxuryCarRental(size, days);  //creates an object i.e. fullsize of class LuxuryCarRental

fullsize.calculateTotal();  //calls calculateTotal method of LuxuryCarRental using instance fullsize

fullsize.print(); }} //calls print() method of LuxuryCarRental using instance fullsize      

Give five types of hardware resource and five types of data or software resource that can usefully be shared. Give examples of their sharing as it occurs in practice in distributed systems.

Answers

Answer:

Answered below

Explanation:

Hardware resources that can be usefully shared and also examples of their sharing include;

A) CPU servers, which carry out computations for clients.

B) Network capacity transmission of data or packet transmission is done using the same circuit, meaning many communication channels share the same circuit.

C) Screen networks windows systems which enable processes in remote computers to update the contents of their local server.

D) Memory cache server.

E) Disk file server, virtual disk server.

Softwares include;

A) Web-page web servers which allow client programs to have read-only access to page contents.

B) Database whose contents can be usefully shared.

C) File servers enable multiple users access to files .

D) Objects can be shared in distributed systems example shared ticket booking, whiteboard etc.

E) Exclusive lock which enables the coordination of accessing a special resource.

Write Album's PrintSongsShorterThan() to print all the songs from the album shorter than the value of the parameter songDuration. Use Song's PrintSong() to print the songs.

Answers

Answer:

Here is the function PrintSongsShorterThan() which prints all the songs from the album shorter than the value of the parameter songDuration.

void Album::PrintSongsShorterThan(int songDuration) const {   //function that takes the songDuration as parameter

unsigned int i;  

Song currSong;    //object of Song

cout << "Songs shorter than " << songDuration << " seconds:" << endl;  

for(int i=0; i<albumSongs.size(); i++){    

currSong = albumSongs.at(i);    

if(currSong.GetDuration()<songDuration){    //checks if the song duration of the song from album is less than the value of songDuration

currSong.PrintSong();     } } }  //calls PrintSong method to print all the songs with less than the songDuration

Explanation:  

I will explain the working of the for loop in the above function.

The loop has a variable i that is initialized to 0. The loop continues to execute until the value of i exceeds the albumSongs vector size. The albumSongs is a Song type vector and vector works just like a dynamic array to store sequences.

At each iteration the for loop checks if the value of i is less than the size of albumSongs. If it is true then the statement inside the loop body execute. The at() is a vector function that is used to return a reference to the element at i-th position in the albumSongs.  

So the album song at the i-th index of albumSongs is assigned to the currSong. This currSong works as an instance. Next the if condition checks if that album song's duration is less than the specified value of songDuration. Here the method GetDuration() is used to return the value of duration of the song. If this condition evaluates to true then the printSong method is called using currSong object. The printSong() method has a statement cout << name << " - " << duration << endl; which prints/displays the name of the song with its duration.

If you see the main() function statement:

musicAlbum.PrintSongsShorterThan(210);  

The musicAlbum is the Album object to access the PrintSongsShorterThan(210) The value passed to this method is 210 which means this is the value of the songDuration.

As we know that the parameter of PrintSongsShorterThan method is songDuration. So the duration of each song in albumSongs vector is checked by this function and if the song duration is less than 210 then the name of the song along with its duration is displayed on the output screen.

For example if the album name is Anonymous and the songs name along with their duration are:

ABC 400  

XYZ 123  

CDE 300  

GHI 200  

KLM 100  

Then the above program displays the following output when the user types "quit" after entering the above information.

Anonymous                                                              

Songs shorter than 210 seconds:                                                                         XYZ - 123                                                                                                              

GHI - 200                                                                                                              

KLM - 100  

Notice that the song name ABC and CDE are not displayed because they exceed the songDuration i.e. 210.

Access controls are enforced automatically in FMS service routines that access and manipulate files and directories.
a True
b. False

Answers

Answer:

A. True

Explanation:

In FMS service routines, access controls are enforced automatically

and they that access and manipulate files and directories. Files and directories are usually accessed via access controls in most of the FMSs.

Additional processing overhead are usually imposed by FMS. Also, the FMS tend to restrict and hinder one from accessing secondary storage.

The Adjacent Coins Problem Published on 2017-08-30 Consider N coins aligned in a row. Each coin is showing either heads or tails. The adjacency of these coins is the number of adjacent pairs of coins with the same side facing up. Write a program that given a non-empty zero-indexed array A consisting of N integers representing the coins, returns the maximum possible adjacency that can be obtained by reversing exactly one coin (that is, one of the coins must be reversed). Consecutive elements of array A represent consecutive coins in the row. Array A contains only 0s and/or 1s:

Answers

Answer:

Here is the JAVA code:

public class Main{

public static int solution(int[] A) { //method that takes non-empty array A consisting of 0s and 1s

           int N = A.length; // number of 0s and 1s in array A

           int r = 0; //result of adjacency

           for (int i = 0; i < N - 1; i++;   )   { // iterates through A

               if (A[i] == A[i + 1])  //if i-th element of A is equal to (i+1)th element

                   r = r + 1;   }     //add 1 to the count of r

           if (r == N-1)   //for test cases like {1,1}

           {return r-1; }

           int max = 0; //to store maximum possible adjacency

           for (int i = 0; i <N; i++)   { //iterates through array

               int c = 0;

               if (i > 0)    { //starts from 1 and  covering the last

                   if (A[i-1] != A[i]) //checks if i-1 element of A is not equal to ith element of A

                       c = c + 1;    //adds 1 to counter variable

                   else

                      c = c - 1;   } //decrements c by 1

               if (i < N - 1)     {//starting with 0

                   if (A[i] != A[i + 1])  //checks if ith element of A is not equal to i+1th element of A

                       c = c + 1; //adds 1 to counter variable

                   else

                       c = c - 1;   }      //decrements c by 1        

               max = Math.max(max,c);   }  //finds the maximum of max and c

           return r + max;         } //returns result + maximum result

        public static void main(String[] args) {

   int[] A = {1, 1, 0, 1, 0, 0}; //sample array to test the method

   System.out.println(solution(A));} } //calls the method passing array to it

Explanation:

The program works as follows:

A[] = {1, 1, 0, 1, 0, 0}

N = A.length

N = 6

The A has the following elements:

A[0] =  1

A[1] = 1

A[2] = 0

A[3] = 1

A[4] = 0

A[5] = 0

Program iterates through array A using for loop. Loop variable i is initialized to 0

if condition if (A[i] == A[i + 1]) checks

if (A[0] == A[0 + 1])

A[0] =  1

A[0 + 1] = A[1] = 1

They both are 1 so they are equal

r = r + 1;  

Since the above if condition is true so 1 is added to the value of r Hence

r = 1

At each iteration of the loop the if condition checks whether the adjacent elements of A are equal. If true then r is incremented to 1 otherwise not.

So after all the iterations value of r = 2

if (r == N-1) evaluates to false because r=2 and N-1 = 5

So program moves to the statement:

for (int i = 0; i <N; i++)

This loop iterates through the array A

if (i > 0) condition checks if value of i is greater than 0. This evaluates to false and program control moves to statement:

if (i < N - 1) which makes if(0<5) This evaluates to true and program control moves to statement

if (A[i] != A[i + 1])  which means:

if (A[0] != A[0 + 1]) -> if (A[0] != A[1])

We know that

A[0] =  1

A[1] = 1

So this evaluates to false and else part is executed:

value of c is decremented to 1. So c=-1

max = Math.max(max,c) statement returns the max of max and c

max = 0

c = -1

So max = 0

value of i is incremented to 1 so i = 1

At next step:

if (i < N - 1) which makes if(1<5) This evaluates to true and program control moves to statement

if (A[i] != A[i + 1]) which means:

if (A[1] != A[1 + 1]) -> if (A[1] != A[2])

A[1] = 1

A[2] = 0

So the statement evaluates to true and following statement is executed

c = c + 1; The value of c is incremented to 1. So

c = -1 + 1

Hence

Hence c= 0, max = 0 and i = 2

next step:

if (i < N - 1) which makes if(2<5) This evaluates to true and program control moves to statement

if (A[i] != A[i + 1]) which means:

if (A[2] != A[2 + 1]) -> if (A[2] != A[3])

A[2] = 0

A[3] = 1

So the statement evaluates to true and following statement is executed

c = c + 1; The value of c is incremented to 1. So

c = 0 + 1

c = 1

Hence

The statement max = Math.max(max,c) returns the max of max and c

max = 0

c = 1

So max = 1

Hence  c= 1, max = 1 and i = 3

next step:

if (i < N - 1) which makes if(3<5) This evaluates to true and program control moves to statement

if (A[i] != A[i + 1]) which means:

if (A[3] != A[3 + 1]) -> if (A[3] != A[4])

A[3] = 1

A[4] = 0

So the statement evaluates to true and following statement is executed

c = c + 1; The value of c is incremented to 1. So

c = 1 + 1

c = 2

Hence

The statement max = Math.max(max,c) returns the max of max and c

max = 1

c = 2

So max = 2

Hence c= 2, max = 2 i = 4

next step:

if (i < N - 1) which makes if(4<5) This evaluates to true and program control moves to statement

if (A[i] != A[i + 1])  which means:

if (A[4] != A[4+ 1]) -> if (A[4] != A[5])

A[4] = 0

A[5] = 0

So this evaluates to false and else part is executed:

value of c is decremented to 1. So c=1

max = Math.max(max,c) statement returns the max of max and c

max = 2

c = 1

So max = 2

value of i is incremented to 1 so i = 5

next step:

if (i < N - 1) which makes if(5<5) This evaluates to false

if (i > 0) evaluates to true so following statement executes:

if (A[i-1] != A[i])

if (A[5-1] != A[5])

if (A[4] != A[5])

A[4] = 0

A[5] = 0

This statement evaluates to false so else part executes and value of c is decremented to 1

Hence

max = 2

c = 0

So max = 2

value of i is incremented to 1 so i = 6

The loop breaks because i <N evaluates to false.

Program control moves to the statement:

return r + max;

r = 2

max = 2

r + max = 2+2 = 4

So the output of the above program is:

4

Declare a struct named PatientData that contains two integer data members named heightInches and weightPounds. Sample output for the given program:Patient data: 63 in, 115 lbs#include using namespace std;/* Your solution goes here */int main() {PatientData lunaLovegood;lunaLovegood.heightInches = 63;lunaLovegood.weightPounds = 115;cout << "Patient data: "<< lunaLovegood.heightInches << " in, "<< lunaLovegood.weightPounds << " lbs" << endl;return 0;}

Answers

Answer:

struct PatientData{

   int heightInches, weightPounds;

};

Explanation:

In order to declare the required struct in the question, you need to type the keyword struct, then the name of the struct - PatientData, opening curly brace, data members - int heightInches, weightPounds;, closing curly brace and a semicolon at the end.

Note that since the object - lunaLovegood, is declared in the main function, we do not need to declare it in the struct. However, if it was not declared in the main, then we would need to write lunaLovegood between the closing curly brace and the semicolon.

For this lab, imagine you are an IT Specialist at a medium-sized company. The Human Resources Department at your company wants you to find out how many people are in each department. You need to write a Python script that reads a CSV file containing a list of the employees in the organization, counts how many people are in each department, and then generates a report using this information. The output of this script will be a plain text file.

Answers

Answer:

import csv

import sys

file_csv = argv

with open( "file_csv", "rb" ) as file:

      rowlist= csv.DictReader( file )

      dict_count={ }

      for row in rowlist:

           dict_count[ row[ 'department' ] ] = dict_count.get( row[ 'department' ], 0 ) + 1

      print( " The count of employees per department are", dict_count )

Explanation:

The python script in the solution above is able to accept user input csv files via command prompt and get an output of the number of employees for each department.

A machine on a 10 Mbps network is regulated by a token bucket algorithm with a fill rate of 3 Mbps. The bucket is initially filled to capacity at 3MB. How long can the machine transmit at the full 10 Mbps capacity

Answers

2+4= this gbhfchgcjdxbhdch is correct


​what are the morals and ethics of computer

Answers

Answer:

Computer ethics is a part of practical philosophy concerned with how computing professionals should make decisions regarding professional and social conduct. Margaret Anne Pierce, a professor in the Department of Mathematics and Computers at Georgia Southern University has categorized the ethical decisions related to computer technology and usage into three primary influences:

The individual's own personal code.

Any informal code of ethical conduct that exists in the work place.

Exposure to formal codes of ethics.

Explanation:

Performing binary search on an unsorted list will always return the correct answer in O(n) time where n is the length of the list.
a) true
b) false

Answers

Answer:

B. False

Explanation:

Binary search does not work in an unsorted list, therefore it will not return the correct answer in 0(n) time.

For an unsorted list, linear search is the better way of searching for algorithms.

For a binary search, it goes through a sorted list to locate a desired element. It repeats its processes until it picks the correct element it is looking for.

3. Which of the following is called address operator?
a)*
b) &
c).
d) %

Answers

Answer:

The Ampersand Symbol (Option B)

Explanation:

A 'address of operator' specifies that a given value that is read needs to be stored at the address of 'x'.

The address operator is represented by the ampersand symbol. ( & )

Hope this helps.

Cloud computing gives you the ability to expand and reduce resources according to your specific service requirement.

a. True
b. False

Answers

Answer:

a. True

Explanation:

Cloud computing can be defined as a type of computing that requires shared computing resources such as cloud storage (data storage), servers, computer power, and software over the internet rather than local servers and hard drives.

Generally, cloud computing offers individuals and businesses a fast, effective and efficient way of providing services.

In Computer science, one of the most essential characteristics or advantages of cloud computing is rapid elasticity.

By rapid elasticity, it simply means that cloud computing gives you the ability to expand and reduce resources according to your specific service requirement because resources such as servers can be used to execute a particular task and after completion, these resources can then be released or reduced.

Some of the examples of cloud computing are Google Slides, Google Drive, Dropbox, OneDrive etc.

The first electric, general-purpose computer, ENIAC, was programmed by calculating algorithms on paper entering code directly into the computer flipping switches by hand using MS-DOS as the operating system

Answers

Complete Question:

The first electric, general-purpose computer, ENIAC, was programmed by?

Group of answer choices.

A. Calculating algorithms on paper.

B. Entering code directly into the computer.

C. Flipping switches by hand.

D. Using MS-DOS as the operating system.

Answer:

C. Flipping switches by hand.

Explanation:

The first electric, general-purpose computer, ENIAC, was programmed by flipping switches by hand.

ENIAC is an acronym for Electronic Numerical Integrator and Computer, it was developed in 1945 by John Mauchly and J. Presber Eckert. ENIAC was used for solving numerical problems or calculation-related tasks by the process of reprogramming.

In order to give the ENIAC a series of machine instructions to follow in the execution of a task, the programmers had to undergo the cumbersome procedure of connecting, removing, reconnecting cables and flipping switches by hand because data couldn't be stored in memory.

what is programming code

Answers

Answer:

Such languages are used to create computer code or program code, the set of instructions forming a computer program which is executed by the computer. This source code is translated into machine code by a compiler or interpreter, so that the computer can execute it to perform its tasks.

Answer:

Writing code,” “coding,” and “programming” are basically interchangeable terms. Broadly speaking, knowing how to write code is the process of creating instructions that tell a computer what to do, and how to do it. Codes are written in various languages, such as javascript, C#, Python, and much more.

hlo samradhiki can we chat in comment section

When you start your computer then which component works first?

Answers

Bios is normally the first software, which is used to initiate connections to the hardware and perform testing and configuration. Then the OS is detected and the whole kernel is handed off to load the OS itself.

#Write a function called fancy_find. fancy_find should have #two parameters: search_within and search_for. # #fancy_find should check if search_for is found within the #string search_within. If it is, it should print the message #"[search_for] found at index [index]!", with [search_for] #and [index] replaced by the value of search_for and the #index at which it is found. If search_for is not found #within search_within, it should print, "[search_for] was #not found within [search_within]!", again with the values #of search_for and search_within. # #For example: # # fancy_find("ABCDEF", "DEF") -> "DEF found at index 3!" # fancy_find("ABCDEF", "GHI") -> "GHI was not found within ABCDEF!"

Answers

Answer:

Here is the Python program:

def fancy_find(search_within , search_for):  # function definition of fancy_find function that takes two parameters

   index = 0  #to store the index of search_within where the search_for string is found

   if search_for in search_within:  #checks if the string search_for is present in string search_within

       sf = search_for[0]  #points to the first character of the search_for

       for sw in search_within:  #iterates through search_within

           if sw == sf:  #if the first character of search_for is equal to the character at sw index of search_within

               if search_within[index:index+len(search_for)] == search_for:  #checks if the value of search_for is found in search_within

                   print(search_for,"found at index",index,"!")  #if above condition is true prints the message "[search_for] found at index [index]!", with [search_for] and [index] replaced by the value of search_for and the index at which it is found

                   return ""  

           index += 1  #increments value of index at each iteration

   print(search_for,"is not found within", search_within)  #if search_for is not found within search_within, prints message "[search_for] was not found within [search_within]!" with the values of search_for and search_within.

   return ""    

#following two statements are used to test the working of above function

print(fancy_find("ABCDEF", "DEF"))  #calls fancy_find() passing "ABCDEF" as search_within and "DEF" as search_for

print(fancy_find("ABCDEF", "GHI")) #calls fancy_find() passing "ABCDEF" as search_within and "GHI" as search_for

Explanation:

The program is well explained in the comments. I will explain the working of the function with the help of an example:

Suppose

search_within = "ABCDEF"

search_for = "DEF"

We have to find if search_for i.e. DEF is present in search_within i.e. ABCDEF

if search_for in search_within statement checks using in operator that if DEF is included in ABCDEF. Here this condition evaluates to true so the next statement sf = search_for[0]  executes which sets the first element of search_for i.e. D to sf. So sf = 'D'

for sw in search_within this statement has a for loop that iterates through ABCDEF and works as following:

At first iteration:

sw contains the first character of search_within  i.e. A

if sw == sf: condition checks if the first character of the search_for i.e. D is equal to sw i.e. A. Its not true so the program control moves to this statement:

index += 1 This increases the value of index by 1. index was initialized to 0 so now it becomes 1. Hence index=1

At second iteration:

sw contains the second character of search_within  i.e. B

if sw == sf: condition checks if the first character of the search_for i.e. D is equal to sw i.e. B Its not true so the program control moves to this statement:

index += 1 This increases the value of index by 1. index was initialized to 0 so now it becomes  2. Hence index=2

At third iteration:

sw contains the third character of search_within  i.e. C

if sw == sf: condition checks if the first character of the search_for i.e. D is equal to sw i.e. C Its not true so the program control moves to this statement:

index += 1 This increases the value of index by 1. index was initialized to 0 so now it becomes  3. Hence index=3

At fourth iteration:

sw contains the third character of search_within  i.e. D

if sw == sf: condition checks if the first character of the search_for i.e. D is equal to sw i.e. D. Its true so so the program control moves to this statement:

  if search_within[index:index+len(search_for)] == search_for:

current value of index=3

len(search_for) returns the length of DEF i.e. 3

So the if condition checks for the search_for in search_within. The statement becomes:

if search_within[3:3+3] == search_for:

search_within[3:3+3]  means from 3rd index position of search_within to 6-th index position of the search_within. This means from 4th element of search_within i.e. D to the last. Hence search_within[3:3+3] is equal to DEF.

search_for = DEF so

if search_within[3:3+3] == search_for: checks if

search_within[3:3+3] = DEF is equals to search_for = DEF

Yes it is true so

print(search_for,"found at index",index,"!") statement is executef which prints the following message:

DEF found at index 3!

This output is because search_for = "DEF" and index=3

Other Questions
What is the difference in their elevations?An airplane flies at an altitude of 26,000 feet. A submarine dives to a depth of 700 feet below sea level Volcanic eruptions are events that take place inside Earths . When they occur on land, they spew tremendous amounts of gas, releasing matter into the . The hot, flowing lava also disrupts the by destroying any vegetation and animals in its path. state one reason many African Americans did not benefit from New Deal programs. A synthetic fiber used in manufactoring dress fabric is? A. Rayon B. Wool C. Cotton D. Silk Payroll deductions are the same for all employees. True False A purebred tall pea plant is cross-pollinated with a tall, heterozygous pea plant. Use a Punnett square to determine the probability the offspring inheritarecessive short allele. (I point)75%25%0%50% solve for x 7(x+2) =6(x+5) If area of a rhombus is 336 cm and one of its diagonal is 14 cm, find its perimeter. All the following statements concerning the interest settlement option in life insurance are correct EXCEPT: Group of answer choices the beneficiary may be allowed to withdraw part or all of the proceeds. the beneficiary may be allowed to change to another settlement option. the minimum guaranteed interest rate usually is equal to the prime rate. the interest can be paid monthly, quarterly, semiannually, or annually. g When considering the effects of temperature on spontaneity, if both H and S are positive, _______. Select the correct answer below: the process is spontaneous at all temperatures past examples of governments that were not democratic? You want to get more physically fit but often make excuses for why you don't have time to be active. What strategy can help with this problem? From her purchased bags, Rory counted 110 red candies out of 550 total candies. Using a 90% confidence interval for the population proportion, what are the lower and upper limit of the interval? Answer choices are rounded to the thousandths place. Two boys and three girls are auditioning to play the piano for a school production. Two students will be chosen, one as the pianist, the other as the alternate.What is the probability that the pianist will be a boy and the alternate will be a girl? Express your answer as a percent.30%40%50%60% Find the solutions to $x^2 + 64 = 0.$[tex]Find the solutions to $x^2 + 64 = 0.$[/tex] a 2-n force is applied to a spring, and there is displacement of 0.4 m. how much would the spring be displaced if a 5-n force was applied? What is the frequency of a photon having an energy of 4.91 1017 ? (c = 3.00 108 m/s, h = 6.63 1034 J s) La seora Nez is giving her boss directions. Complete the sentences by choosing the correct formal command. ____ derecho hasta llegar al monumento. a. Siga g If A and B are disjoint events, with P( A) = 0.20 and P( B) = 0.30. Then P( A and B) is: a. .00 b. .10 c. .50 d. 0.06 Which of the following pairs of chemical reactions are inverses of each other? Answer options: a. Hydrogenation and alkylation b.Halogenation and hydrolysis c. Ammoniation and alkylation d. Oxidation and reduction