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.

Answers

Answer 1

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.

Answer 2

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


Related Questions

In this task, you will perform normalization on a crude table so that it could be stored as a relational database.

The staff at 'Franklin Consulting' have to routinely visit their clients in other cities. Franklin have a fleet of cars available for staff travels. During their trips, the staff sometimes need to fill up the car fuel. Upon returning from the trip, the staff claim that expenses back by providing the fueling receipt and some other essential information. The accountant records all of that information in a spreadsheet. Below are the spreadsheet column headers and a sample of data from each column.

Column Name

Example Data

Trip ID

4129

Staff name

Sarah James

Car details

Toyota Land Cruiser 2015

License Plate

1CR3KT

Odometer reading

25,067

Service station

Coles Express

Station address

27 Queen St, Campbelltown, NSW 2560

Fill up time

30 Jan 2020, 2:45 pm

Fuel type

Unleaded 95

Quantity litres

55

Cost per litre

$1.753

Total paid

$96.42
Given the information in above table,

1. Draw a dependency diagram to show the functional dependencies existing between columns. State any assumptions you make about the data and the attributes shown in the table. (3 marks)

2. Show the step by step process of decomposing the above table into a set of 3NF relations. (5 marks)

3. Review the design of your 3NF relations and make necessary amendments to define proper PKs, FKs and atomic attributes. Any additional relations may also be defined at this stage. Make sure all of your attributes conform to the naming conventions. (3 marks)

4. Draw the Crow’s Foot ERD to illustrate your final design. (4 marks)

Answers

Answer:

Check the explanation

Explanation:

(1.) The functional dependencies based on assumptions are as follows:-

Trip determines which staff was there in the trip, the car used for the trip, the quantity of fuel used in the trip, the fill up time and the total paid of the trip.

Service station refers to its address

Car details consist of the details of license plate, odometer reading and the fuel type used in the car

fuel type and the fill up time will help to determine the cost of the fuel at that time

cost of the fuel and the quantity of fuel used will determine the total paid

From the above assumptions the functional dependencies are as follows:-

Trip ID -> Staff Name, Car Details, Service Station, Quantity, Fill Up Time, Total Paid

Service Station -> Station Address,

Car Details -> License Plate, Odometer reading, Fuel Type

Fuel Type, Fill up Time -> Cost per litre

Cost per Litre, Quantity -> Total Paid

(2.) Initially the relation is as follows:-

R (Trip ID, Staff Name, Car Details, License Plate, Odometer Reading, Service Station, Station Address, Fill up Time, Fuel type, Quantity, Cost per Litre, Total Paid)

For 1 NF there should not be composite attributes,in the above relation Staff Name and Station Address are composite attributes therefore it will be decomposed as follows:-

R (Trip ID, Staff First Name,Staff Last Name, Car Details, License Plate, Odometer Reading, Service Station, Street, City, State, Zip Code, Fill up Time, Fuel type, Quantity, Cost per Litre, Total Paid)

For 2 NF there should not be partial dependency that is non prime attribute should not dependent upon any 1 prime attribute of candidate key, since in the given relation there is only 1 candidate key which is only Trip ID, therefore the relation is already in 2 NF.

For 3 NF there should not be transitive dependency that is non prime attribute should not dependent upon the other non prime attribute, if it is present then the relation will be decomposed into sub relations, the given relation is not in 3 NF therefore it will be decomposed as follows:-

R1 (Trip ID, Staff First Name, Staff Last Name, Car Details, Service Station, Quantity, Fill up time, Total paid)

R2 (Service Station, Street, City, State, Zip Code)

R3 (Car Details, License Plate, Odometer reading, Fuel Type)

R4 (Fuel Type, Fill up Time, Cost per litre)

R5 (Cost per Litre, Quantity, Total Paid)

(3.) After the 3 NF we add the primary and foreign key constraints as follows:-

R1 (Trip ID, Staff First Name, Staff Last Name, Car Details, Service Station, Quantity, Fill up time, Total paid)

R2 (Service Station, Street, City, State, Zip Code)

R3 (Car Details, License Plate, Odometer reading, Fuel Type)

R4 (Fuel Type, Fill up Time, Cost per litre)

R5 (Cost per Litre, Quantity, Total Paid)

In the above relational schema the primary keys are represented with bold and foreign keys by italic

(4.) The ER diagram of the above relational schema using crow's foot notation are as shown in the attached image below:-

Suppose that you sort a large array of integers by using a merge sort. Next you use a binary search to determine whether a given integer occurs in the array. Finally, you display all of the integers in the sorted array. a. Which algorithm is faster, in general: the merge sort or the binary search? Explain in terms of Big O notation. b. Which algorithm is faster, in general: the binary search or displaying the integers? Explain in terms of Big O notation.

Answers

Answer:

See explaination

Explanation:

Merge sort working-

1.type of recursive sorting algorithm.

2.divides given array into halves.

3. Sort each halves. Merge this halves to give a sorted array.

4. Recursive call continues till array is divided and each piece has only one element.

5. Merge this small pieces to get a sorted array.

Binary search-

1. It is a search algorithm.

2. Requires a sorted array to work on.

3.Works repetively dividing a half portion of list that could contain item until it has narrowed down the possible location to just one.

Comparing Merge sort and Binary Search using Big O notation-

Merge Sort - O(n*log(n)) in all scenario whether best, average or worst case.

Binary Search- O(log(n)) in average and worst case. O(1) in best case.

So seeing the above comparison Binary search is faster.

Comparing Binary search and displaying the integers-

Binary Search- O(log(n)) in average and worst case. O(1) in best case.

Displaying the integer-O(1) if already initialized, O(n) in case of loop or function.

So seeing above one can conclude that binary search is fast. But in best case both works in a similar manner.

List 3 specific uses for an Excel spreadsheet in the field you are going into. Give specific examples of how you could or have used Excel in the field. Choose examples that you are familiar with, remembering that personal stories always makes a post more interesting

Answers

Answer:

The answer to this question can be defined as below:

Explanation:

The three uses of the spreadsheet can be described as follows:

In Business:

All organizations use Excel, which uses daily by Microsoft Excel, as a key feature of the Microsoft Office company Desktop Suite. Spreadsheets preparation manuals contain worksheets for documents and tablets.

In Auditing:

It is a function, that be can provide you with several methods for inspecting by constructing 'short cuts' obstacles. Multiple functions have been helpful, and that you have reduced returns with the time it takes for something to be hung up.

In nursing:

All related to figures should be available in a list. Health staff may very well use them to calculate their patients, profits and costs. You should keep a list of clients and medication. They may have to keep hospital-based, clients are at the healing facility on weekends, subtle features of hours employed by medical staff and various items.

(a) Implement (in Java) the RadixSort algorithm to sort in increasing order an array of integer keys.

public void radixSort(int arr[])

In your implementation you must consider that each key contains only even digits (0, 2, 4, 6, and 8). Your program must detect the case of odd digits in the keys, and, in this case, abort.

Note: To storage and process the bucket lists, use an ArrayList structure.

(b) What is the running time complexity of your radixSort method? Justify.

Answers

‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎   ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎ .‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎  ‏‏‎

Final answer:

The provided response includes a Java implementation of the radixSort algorithm that sorts an array of integers with only even digits and aborts if odd digits are found. The running time complexity is O(nk) but is effectively O(n) due to the fixed set of digits.

Explanation:

The student has asked to implement the radixSort algorithm in Java, which sorts an array of integers containing only even digits (0, 2, 4, 6, and 8). Moreover, the program should abort if odd digits are present in the keys. Here's an example implementation:

import java.util.ArrayList;

class RadixSortExample {
   public void radixSort(int[] arr) {
       final int RADIX = 10;

       // Find the maximum number to know the number of digits
       int max = arr[0];
       for (int i = 1; i < arr.length; i++) {
           if (arr[i] > max) max = arr[i];
       }

       // Abort if odd digits found
       for (int num : arr) {
           if (containsOddDigit(num)) {
               throw new IllegalArgumentException("Array contains odd digits, which is not allowed.");
           }
       }

       // Perform sorting
       for (int exp = 1; max / exp > 0; exp *= RADIX) {
           countSort(arr, exp);
       }
   }

   private void countSort(int[] arr, int exp) {
       ArrayList<ArrayList<Integer>> bucketList = new ArrayList<>(10);
       for (int i = 0; i < 10; i++) {
           bucketList.add(new ArrayList<>());
       }

       // Distribute the numbers based on the digit at the given exponent
       for (int num : arr) {
           int bucketIndex = (num / exp) % 10;
           bucketList.get(bucketIndex).add(num);
       }

       // Merge the buckets
       int index = 0;
       for (int i = 0; i < 10; i++) {
           for (int num : bucketList.get(i)) {
               arr[index++] = num;
           }
       }
   }

   private boolean containsOddDigit(int num) {
       while (num > 0) {
           if ((num % 10) % 2 != 0) return true;
           num /= 10;
       }
       return false;
   }
}

As for the running time complexity of the radixSort method, it is O(nk), where n is the number of keys and k is the number of digits in the maximum key. The algorithm runs digit by digit, but since we're dealing with a fixed set of digits (even digits only), the k value is bounded and the complexity can also be seen as O(n) for practical considerations, especially when the range of the input is restricted.

In this assignment you will write a function that will calculate parallel resistance for up to 10 parallel resistors. Call the function by ParallelR(Number), where Number is an integer between 1 and 10 which will be input from a command window prompt. Use a for loop Number times to find the Numerator and Denominator for parallel resistance. After the for loop you should find Solution as Num/Den. the number Solution will be returned by the function.

Answers

Answer:

See explaination

Explanation:

format RAT

Number=input('Enter the no. of resistors:');

R=ParallelR(Number)

function Req=ParallelR(N)

R=0;

for i=1:N

r=input('Enter Resistor Value:');

R=R+1/r;

end

Req=(1/R);

end

Write a function that takes an integer, val, as an argument. The function asks the user to enter a number. If the number is greater than val, the function displays Too high. and returns 1; if the number is less than val, the function displays Too low. and returns –1; if the number equals val, the function displays Got it! and returns 0. Call the function repeatedly until the user enters the right number.

Answers

Answer:

import java.util.*;

public class num2 {

   public static void main(String[] args) {

       //Set the Value of the argument

       int val = 5;

       //Call the method

       int returnedNum = testInteger(val);

       //Use a While to continously call the method as long as the returned value is not 0

       while(returnedNum != 0){

           int rt = testInteger(val);

           //Break out of loop when the user enters correct value and the return is 0

           if(rt == 0){

               break;

           }

       }

   }

   //The Method definition

   public static int testInteger(int val){

       //Prompt and receive user input

       System.out.println("Enter a number");

       Scanner in = new Scanner(System.in);

       int userNum = in.nextInt();

       //Check different values using if and else statements

       if(userNum > val){

           System.out.println("Too High");

           return 1;

       }

       else if(userNum < val){

           System.out.println("Too Low");

           return -1;

       }

       else{

           System.out.println("Got it");

         return 0;

       }

   }

}

Explanation:

This is solved with Java Programing Language

Pay close attention to the comments provided in the code

The logic is using a while loop to countinually prompt the user to enter a new number as long as the number entered by the user is not equal to the value of the argument already set to 5.

Answer:

def high_low(val):

   number = int(input("Enter a number: "))

   if number > val:

       print("Too high")

       return 1

   elif number < val:

       print("Too low")

       return -1

   elif number == val:

       print("Got it!")

       return 0

   

val = 7

while True:

   if high_low(val) == 0:

       break

Explanation:

The code is in Python.

Create a function called high_low that takes one parameter, var

Ask the user for a number. Check the number. If the number is greater than 1, smaller than 1 or equal to 1. Depending on the number, print the required output and return the value.

Set the value to a number. Create a while loop iterates until the user enters the correct number, when the return value of the function is equal to 0, that means the user entered the correct number. Otherwise, it keeps asking the number and prints the appropriate message.

Write a program to read 10 integers from an input file and output the average, minimum, and maximum of those numbers to an output file. Take the name of the input file and output file from the user. Make sure to test for the conditions 1. if the count of numbers is less than 10 in the input file, then your average should reflect only for that many numbers 2. if the count of numbers is more than 10 in the input file, then your average should reflect only for ten numbers only.

Answers

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;

}

Write a method manyStrings that takes an ArrayList of Strings and an integer n as parameters and that replaces every String in the original list with n of that String. For example, suppose that an ArrayList called "list" contains the following values:("squid", "octopus")And you make the following call:manyStrings(list, 2);Then list should store the following values after the call:("squid", "squid", "octopus", "octopus")As another example, suppose that list contains the following:("a", "a", "b", "c")and you make the following call:manyStrings(list, 3);Then list should store the following values after the call:("a", "a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c")You may assume that the ArrayList you are passed contains only Strings and that the integer n is greater than 0.

Answers

Answer:

public static ArrayList manyStrings(ArrayList<String> list, int n){

    ArrayList<String> newList = new ArrayList<String>();

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

        for (int j=0; j<n; j++) {

            newList.add(list.get(i));

        }

    }

    return newList;

}

Explanation:

Create a method called manyStrings that takes two parameters, list and n

Create a new ArrayList that will hold new values

Create a nested for loop. The outer loop iterates through the list. The inner loop adds the elements, n of this element, to the newList.

When the loops are done, return the newList

What output will be produced by the following code?
public class SelectionStatements { public static void main(String[] args)
{ int number = 25; if(number % 2 == 0)
System.out.print("The condition evaluated to true!");
else
System.out.print("The condition evaluated to false!"); } }

Answers

Answer:

The condition evaluated to false!

Explanation:

lets attach line numbers to the given code snippet

public class SelectionStatements {    public static void main(String[] args) {    int number = 25;    if(number % 2 == 0)    System.out.print("The condition evaluated to true!");    else    System.out.print("The condition evaluated to false!");    } }In Line 3: An integer number is declared and assigned the value 25Line 4 uses the modulo operator (%) to check if the number (25) is evenly divided by 2. This however is not true, so line 5 is not executedThe else statement on line 6- 7 gets executed

Write a program that takes as input an arithmetic expression followed by a semicolon ";". The program outputs whether the expression contains matching grouping symbols. For example, the arithmetic expressions {25 + (3 – 6) * 8} and 7 + 8 * 2 contains matching grouping symbols. However, the expression 5 + {(13 + 7) / 8 - 2 * 9 does not contain matching grouping symbols. If the expression contains matching grouping symbols, the program output should contain the following text: Expression has matching grouping symbol If the expression does not contain matching grouping symbols, the program output should contain the following text:

Answers

Answer:

See explaination for the details of the answer.

Explanation:

#include <iostream>

#include <stack>

using namespace std;

int main(){

string str;

cout<<"Enter a String: ";

std::getline (std::cin,str);

bool flag=true;

stack<char> st;

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

if( (str.at(i)>='0' && str.at(i)<='9') || str.at(i)=='+' || str.at(i)=='-' || str.at(i)=='/'|| str.at(i)=='*' || str.at(i)==' ' ){

// cout<<str.at(i) <<"came"<<endl;

continue;

}

if( str.at(i)=='{' || str.at(i)=='(' ){

st.push(str.at(i));

}

else if(!st.empty() &&((st.top() == '{' && str.at(i) == '}') || (st.top() == '(' && str.at(i) == ')')))

st.pop();

else{

flag=false;

break;

}

}

if(!st.empty()){

cout<<"Does not match"<<"\n";

}else{

if(flag)

cout<<"Match"<<"\n";

else

cout<<"Does not match"<<"\n";

}

return 0;

}

See attachment for the output.

Open IDLE. Create a new script file (File-->New File, Ctrl n on Windows, Cmd n on macOS). On the first line, place your name in a comment. Create a program that does the following: Requests an integer number from the user This number will determine the number of rows that will be displayed Print out a header row Displays the current row number, that number multiplied by ten, then multiplied by 100, then multiplied by 1000, in tabular format Repeat this until the required number of rows have been displayed This program must account for the user having stated zero (0) rows should be displayed Your output should resemble the following: Python Output 5

Answers

Answer:

program:

#your name

print("{:10} {:10} {:10}".format("Number","Square","Cube"))

print("{:<10} {:<10} {:<10}".format(0,0,0))

print("{:<10} {:<10} {:<10}".format(1,1,1))

print("{:<10} {:<10} {:<10}".format(2,2**2,2**3))

print("{:<10} {:<10} {:<10}".format(3,3**2,3**3))

print("{:<10} {:<10} {:<10}".format(4,4**2,4**3))

print("{:<10} {:<10} {:<10}".format(5,5**2,5**3))

print("{:<10} {:<10} {:<10}".format(6,6**2,6**3))

print("{:<10} {:<10} {:<10}".format(7,7**2,7**3))

print("{:<10} {:<10} {:<10}".format(8,8**2,8**3))

print("{:<10} {:<10} {:<10}".format(9,9**2,9**3))

print("{:<10} {:<10} {:<10}".format(10,10**2,10**3))

output:

Number Square Cube

0 0 0

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

Design and implement a GUI application that uses text fields to obtain two integer values (one text field for each value) along with a button named "display" to display the sum and product of the values. Assume that the user always enters valid integer values as inputs.

Answers

Answer:

Public Class Form1

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

       Dim sum, product, num1, num2 As Integer

       num1 = Val(TextBox1.Text)

       num2 = Val(TextBox2.Text)

       sum = num1 + num2

       product = num1 * num2

       TextBox3.Text = sum

       TextBox4.Text = product

   End Sub

End Class

Explanation:The solution is implemented in Visual Basic Programming LanguageTwo textboxes are created to receive the user's input and two textboxes for displaying sum and product respectivelyEach of these controls are appropriately labeled (See the attached GUI interface)The Sum is calculated by adding the values from textbox1 and 2The product is calculated by multiplying both

An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a–z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing".
As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment.
fading trailing batting
Write the code segment as described above. The code segment must use an enhanced for loop.

Answers

Answer:

Explanation:

#include <iostream>

using namespace std;

int main()

{

   string cwords[8]={"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"};

   string temp="";

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

   {

       temp=cwords[i];

       int j=temp.length();

       if (temp[j-3]=='i' && temp[j-2]=='n' && temp[j-1]=='g')

       {

           cout<<temp<<endl;

       }

   }

   return 0;

}

The code segments must use an enhanced for loop given in the coding language.

What are code segments?

A code segment is a chunk of an object file or the corresponding area of the program's source code that is used for programming. It is also referred to as a text segment or simply as text.

#include <iostream>

using namespace std;

int main()

{

  string cwords[8]={"ten", "fading", "post", "card", "thunder", "hin-ge", "trailing", "batting"};

  string temp="";

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

  {

      temp=cwords[i];

      int j=temp.length();

      if (temp[j-3]=='i' && temp[j-2]=='n' && temp[j-1]=='g')

      {

          cout<<temp<<endl;

      }

  }

return 0;

}

Therefore, the code segments are written above.

To learn more about code segments, refer to the link:

https://brainly.com/question/20063766

#SPJ2

6.4 Predicting Prices of Used Cars. The file ToyotaCorolla.csv contains data on used cars (Toyota Corolla) on sale during late summer of 2004 in the Netherlands. It has 1436 records containing details on 38 attributes, including Price, Age, Kilometers, HP, and other specifications. The goal is to predict the price of a used Toyota Corolla based on its specifications. (The example in Section 6.3 is a subset of this dataset.) Split the data into training (50%), validation (30%), and test (20%) datasets. Run a multiple linear regression with the outcome variable Price and predictor variables Age_08_04, KM, Fuel_Type, HP, Automatic, Doors, Quarterly_ Tax, Mfr_Guarantee, Guarantee_Period, Airco, Automatic_airco, CD_Player, Powered_Windows, Sport_Model, and Tow_Bar. a. What appear to be the three or four most important car specifications for predicting the car’s price?

Answers

Answer:

Compare the predictions in terms of the predictors that were used, the magnitude of the difference between the two predictions, and the advantages and disadvantages of the two methods.

Our predictions for the two models were very simmilar. A difference of $32.78 (less than 1% of the total price of the car) is statistically insignificant in this case. Our binned model returned a whole number while the full model returned a more “accurate” price, but ultimately it is a wash. Both models had comparable accuracy, but the full regression seemed to be better trained. If we wanted to use the binned model I would suggest creating smaller bin ranges to prevent underfitting the model. However, when considering the the overall accuracy range and the car sale market both models would be

Explanation:

JAVA PROGRAMMING

Arrays are useful to process lists.

A top-level domain (TLD) name is the last part of an Internet domain name like .com in example.com. A core generic top-level domain (core gTLD) is a TLD that is either .com, .net, .org, or .info. A restricted top-level domain is a TLD that is either .biz, .name, or .pro. A second-level domain is a single name that precedes a TLD as in apple in apple.com.

The following program repeatedly prompts for a domain name, and indicates whether that domain name consists of a second-level domain followed by a core gTLD. Valid core gTLD's are stored in an array. For this program, a valid domain name must contain only one period, such as apple.com, but not support.apple.com. The program ends when the user presses just the Enter key in response to a prompt.

1-Run the program and enter domain names to validate.

2-Extend the program to also recognize restricted TLDs using an array, and statements to validate against that array. The program should also report whether the TLD is a core gTLD or a restricted gTLD. Run the program again.

import java.util.Scanner;

public class GtldValidation {

public static void main (String [ ] args) {
Scanner scnr = new Scanner(System.in);

// Define the list of valid core gTLDs
String [ ] validCoreGtld = { ".com", ".net", ".org", ".info" };
// FIXME: Define an array named validRestrictedGtld that has the names
// of the restricted domains, .biz, .name, and .pro
String inputName = "";
String searchName = "";
String theGtld = "";
boolean isValidDomainName = false;
boolean isCoreGtld = false;
boolean isRestrictedGtld = false;
int periodCounter = 0;
int periodPosition = 0;
int i = 0;

System.out.println("\nEnter the next domain name ( to exit): ");
inputName = scnr.nextLine();

while (inputName.length() > 0) {

searchName = inputName.toLowerCase();
isValidDomainName = false;
isCoreGtld = false;
isRestrictedGtld = false;

// Count the number of periods in the domain name
periodCounter = 0;
for (i = 0; i < searchName.length(); ++i) {
if (searchName.charAt(i) == '.') {
++periodCounter;
periodPosition = i;
}
}

// If there is exactly one period that is not at the start
// or end of searchName, check if the TLD is a core gTLD or a restricted gTLD
if ((periodCounter == 1) &&
(searchName.charAt(0) != '.') &&
(searchName.charAt(searchName.length() - 1) != '.')) {
isValidDomainName = true;
}
if (isValidDomainName) {
// Extract the Top-level Domain name starting at the period's position. Ex:
// If searchName = "example.com", the next statement extracts ".com"
theGtld = searchName.substring(periodPosition);

i = 0;
while ((i < validCoreGtld.length) && (!isCoreGtld)) {
if(theGtld.equals(validCoreGtld[i])) {
isCoreGtld = true;
}
else {
++i;
}
}

// FIXME: Check to see if the gTLD is not a core gTLD. If it is not,
// check to see whether the gTLD is a valid restricted gTLD.
// If it is, set isRestrictedGtld to true

}

System.out.print("\"" + inputName + "\" ");
if (isValidDomainName) {
System.out.print("is a valid domain name and ");
if (isCoreGtld) {
System.out.println("has a core gTLD of \"" + theGtld + "\".");
}
else if (isRestrictedGtld) {
System.out.println("has a restricted gTLD of \"" + theGtld + "\".");
}
else {
System.out.println("does not have a core gTLD."); // FIXME update message
}
}
else {
System.out.println("is not a valid domain name.");
}

System.out.println("\nEnter the next domain name ( to exit): ");
inputName = scnr.nextLine();
}

return;
}
}

Answers

Answer:

See explaination

Explanation:

import java.util.Scanner;

public class GtldValidation {

public static void main (String [ ] args) {

Scanner scnr = new Scanner(System.in);

// Define the list of valid core gTLDs

String [ ] validCoreGtld = { ".com", ".net", ".org", ".info" };

// FIXME: Define an array named validRestrictedGtld that has the names

// of the restricted domains, .biz, .name, and .pro

String [] validRestrictedGtld={".biz",".name",".pro"};

String inputName = "";

String searchName = "";

String theGtld = "";

boolean isValidDomainName = false;

boolean isCoreGtld = false;

boolean isRestrictedGtld = false;

int periodCounter = 0;

int periodPosition = 0;

int i = 0;

System.out.println("\nEnter the next domain name (<Enter> to exit): ");

inputName = scnr.nextLine();

while (inputName.length() > 0) {

searchName = inputName.toLowerCase();

isValidDomainName = false;

isCoreGtld = false;

isRestrictedGtld = false;

// Count the number of periods in the domain name

periodCounter = 0;

for (i = 0; i < searchName.length(); ++i) {

if (searchName.charAt(i) == '.') {

++periodCounter;

periodPosition = i;

}

}

// If there is exactly one period that is not at the start

// or end of searchName, check if the TLD is a core gTLD or a restricted gTLD

if ((periodCounter == 1) &&

(searchName.charAt(0) != '.') &&

(searchName.charAt(searchName.length() - 1) != '.')) {

isValidDomainName = true;

}

if (isValidDomainName) {

// Extract the Top-level Domain name starting at the period's position. Ex:

// If searchName = "example.com", the next statement extracts ".com"

theGtld = searchName.substring(periodPosition);

i = 0;

while ((i < validCoreGtld.length) && (!isCoreGtld)) {

if(theGtld.equals(validCoreGtld[i])) {

isCoreGtld = true;

}

else {

++i;

}

}

// FIXME: Check to see if the gTLD is not a core gTLD. If it is not,

// check to see whether the gTLD is a valid restricted gTLD.

// If it is, set isRestrictedGtld to true

}

System.out.print("\"" + inputName + "\" ");

if (isValidDomainName) {

System.out.print("is a valid domain name and ");

if (isCoreGtld) {

System.out.println("has a core gTLD of \"" + theGtld + "\".");

}

else if (isRestrictedGtld) {

System.out.println("has a restricted gTLD of \"" + theGtld + "\".");

}

else {

System.out.println("does not have a core gTLD."); // FIXME update message

}

}

else {

System.out.println("is not a valid domain name.");

}

System.out.println("\nEnter the next domain name (<Enter> to exit): ");

inputName = scnr.nextLine();

}

return;

}

}

8.17 Lab: Strings of a Frequency Write a program that reads whitespace delimited strings (words) and an integer (freq). Then, the program outputs the strings from words that have a frequency equal to freq in a case insensitive manner.

Answers

The program reads whitespace-delimited strings and an integer frequency, then outputs strings with the specified frequency in a case-insensitive manner using a frequency counting approach.

In this programming task, the goal is to create a program that reads whitespace-delimited strings and an integer frequency (freq). The program should then output the strings from the input that have a frequency equal to the specified freq in a case-insensitive manner.

To achieve this, the program needs to:

1. Read input: Use an input mechanism to read whitespace-delimited strings and the integer frequency.

2. Count frequency: Maintain a data structure, such as a dictionary or a hashmap, to store the frequency of each string. While reading the input strings, update the frequency count accordingly.

3. Filter strings: Iterate through the stored strings and output only those with a frequency equal to the specified freq. Ensure case-insensitivity by converting all strings to lowercase during comparison.

Here's a Python example:

```python

def find_strings_with_frequency(words, freq):

   word_count = {}    

   # Count the frequency of each word

   for word in words:

       word_lower = word.lower()

       word_count[word_lower] = word_count.get(word_lower, 0) + 1    

   # Output strings with the specified frequency

   result = [word for word, count in word_count.items() if count == freq]    

   return result

# Example usage

input_words = input("Enter whitespace-delimited strings: ").split()

input_freq = int(input("Enter frequency: "))

output_strings = find_strings_with_frequency(input_words, input_freq)

print("Strings with frequency {}: {}".format(input_freq, output_strings))

```

This program takes user input for whitespace-delimited strings and an integer frequency, processes the input, and outputs strings with the specified frequency in a case-insensitive manner.

Suppose you are an art thief (not a good start) who has broken into an art gallery. All you have to haul out your stolen art is your briefcase which holds only W pounds of art and for every piece of art, you know its weight. Write a program that contains a dynamic programming function to determine your maximum profit. Include a main program that tests your function against each of the following two data sets (each happens to have n=5 items; but your function should work for other values of n as well; we are likely to test your code against another random dataset with an unknown number of items):

Data set 1:

Items 1, 2, 3, 4, and 5 have weights 2, 3, 4, 5 , 9 and value 3, 4, 8, 8, and 10, respectively. Let W = 20.

Data set 2:

Items 1, 2, 3, 4, and 5 have weights 1, 2, 5, 6, 7 and value 1, 6, 18, 22, and 28, respectively. Let W = 11.

Answers

Answer:

Check the explanation

Explanation:

weights = [2,3,4,5,9] #assign the weights here

value = [3,4,8,8,10] #assign the values here

#recursive function to get the maximum weight for a given knapsack

def getMaxWeight(weights,value,W,n):

#check if any elements are there or check if the knapsack can hold any more weights

if(n==0 or W==0):

return 0

elif(weights[n]>W):

#if the current value of the weight is greater than what a knapsack can hold then discard that

return getMaxWeight(weights,value,W,n-1)

else:

#either choose the current weight or do not choose based on the maximum values

return max(value[n]+getMaxWeight(weights,value,W-weights[n],n-1),getMaxWeight(weights,value,W,n-1))

if __name__ == '__main__':

W=20

n=len(weights)-1

print("Weights are:",weights)

print("Values are:",value)

print("Maximum value for given knapsack is:",getMaxWeight(weights,value,W,n))

Kindly check the attached output images below.

Given the following SQL Query, which columns would you recommend to be indexed? SELECT InvoiceNumber, InvoiceDate, Invoice_Total, Invoice_Paid, Invoice_Total - Invoice_Paid as Balance FROM Invoice WHERE Invoice_Date >= "2015-07-20" and Salesman_Id = "JR" ORDER BY DESC Invoice_Total Drag the correct answers to one of the three pockets.

Answers

Answer:

Invoice_Date and Salesman Id

Explanation:

As the WHERE clause looking at the Invoice_Date and Salesman Id columns so they should be indexed for the following reasons.

Uniquely identifiable records are guaranteed by the unique indexes in the database.Data can be quickly retrieved.The usage of indexes results in much better performance.It can help with quick presorted list of records.

Answer the following Python Interview questions • How is Python an interpreted language? • What is the difference between Python Arrays, lists, tuples, and records? Explain it with examples • What does [::-1] do? Explain it with an example • How can you randomize the items of a list in place in Python? • What is the difference between range & xrange?Explain it with an example • What advantages do NumPy arrays offer over (nested) Python lists? • How to add values to a python array? Explain it with an example • What is split used for? Explain it with an example

Answers

Answer:

1. Python is called as interpreted language. However as a programming language it is not fully compiled nor interpreted language. Python program runs from direct source code which makes it byte code interpreted.

An Interpreter is the one which takes the code and performs the actions specified in the code. It turns the code into intermediate language which is again translated to machine language understood by the processor. Interpreted or compiled are the property of the implementation and not of the language.

2. Array : It is a collection of same data type elements stored at contagious memory location. It is handled in python with module array. All the elements of array must be of same data type. In order to manipulate same data types arrays are used.

Ex: array1 = a.array ('i', [10, 20, 30]) this is a array of integer type.

Lists : Python lists are ordered data structure and are like non homogeneous dynamic sized arrays. It may contain integers, strings, boolean, or objects.

Ex: List1 = [70, 89, 98] , List2 = ["Rose", "Lilly", "Jasmine"]

List3 = [1, 10, 100, 'Test', 'Test1']

Tuple : It is a collection of objects separated by commas and they are immutable. It is static which makes them faster.

Ex: tupule1 = ('element1', 'element2')

List and Tuple in Python are the class of data structure. The list is dynamic, whereas tuple has static characteristics.

Lists are mutable but tuples are not.

tuples are mainly used to access the elements where as lists are used in operations like insertion and deletion.

Iterations are time consuming in list where as it is faster in tuples.

tuples don't have inbuilt methods but list has many builtin methods.

tuples takes slightly less memory that lists in Python

Records: Records data structure will have fixed number of fields and each field may have a name and different type. Immutable records are implemented using named tuple.

3. Syntax of slice in python is list[<start>:<stop>:<step>] and it can be used on tuples and lists.

so X [::-1] means that it will start from the end towards the first element by taking each of the elements.

for ex: X = '9876'

X [::-1] will result in '6789'.

Means it will reverse all the elements in the array.

4. Items of list can be shuffled with the random.shuffle() function of a random module.

Syntax is : random.shuffle(x, random)

x- It is a sequence to shuffle and can be list or tuple.

random- it is a optional argument which returns random float number between 0.1 to 1.0.

5. range() – Range function returns a range object which is a type of iterable object.

xrange() – xrange function returns the generator object that can be used to display numbers only by looping. Only particular range is displayed on demand and hence called “lazy evaluation“.

• Return type of range () is range object whereas that of xrange() is xrange object.

• Variable to store the range using range () takes more memory but xrange takes comparative less memory.

• Range returns the list but xrange returns the xrange object. Hence operations on list can be applied for range but not on xrange.

• Xrange is faster to implement than range as xrange evaluates only generator objects.

• Xrange is depreciated in Python 3 and above.

For ex :

x = range (10, 100)

y= xrange (10, 100)

#To know the return type we can print it

print ( return type of range () is : “)

print (type (x))

print ( return type of xrange () is : “)

print (type (y))

Output will be list and xrange respectively.

6. NumPy's arrays are more compact than Python lists

reading and writing items is also faster with NumPy.

Memory taken by python lists are way higher than NumPy arrays.

Python lists don’t support vectorized operation.

Since lists can contain objects of different types its type information must be stored and executed every time operation is performed on it.

Memory taken by python lists are a lot higher than that of NumPy Arrays.

Reading and writing of elements in NumPy arrays are faster than lists.

NumPy arrays are compact and accumulate lesser storage.

Numpy is convenient and efficient.

For ex :

Metrics operations are easy in NumPy.

Checkerboard pattern can be done using NumPy.

7. Attached as Image

8. split() method returns a list of strings after breaking the given string by the specified separator. It is splitting of string into list with each word is a list item.

Syntax : str.split ( separator, maxsplit)

Separator : its is delimiter used and by default whitespace is used as separator.

Maxsplit : Maximum number of times to split the string. By default it has no limit.

For ex:

text = 'apples and oranges are different '

print(text.split())

output will be : ['apples', 'and', 'oranges', 'are', 'different' ]

Explanation:

Answer:

It Is C to shorten it The answer is C

Explanation:

Provided below is the implementation of the hashtable data structure we went over together in class. You are to implement the rehash method, which will be called with a new size for the internal buckets array. rehash will create a new buckets array, copy all the key/value pairs from the old buckets array into the new one, using linked list chains as before to support collisions, then switch to using the new buckets array. rehash should run in O(N) time, where N is the number of key/value pairs,. Your implementation of rehash should not make use of any other hashtable or list methods (other than those demonstrated in __setitem__ and __getitem__). Note that the first and last lines of rehash are given; you should not alter them.

Answers

Answer:

numBuckets = 47

def create():

global numBuckets

hSet = []

for i in range(numBuckets):

hSet.append([])

# print "[XYZ]: create() hSet: ", hSet, " type(hSet): ",type(hSet)

return hSet

def hashElem(e):

global numBuckets

return e % numBuckets

def insert(hSet,i):

hSet[hashElem(i)].append(i)

# print "[XYZ]: insert() hSet: ", hSet, " type(hSet): ",type(hSet)

def remove(hSet,i):

newBucket = []

for j in hSet[hashElem(i)]:

if j != i:

newBucket.append(j)

hSet[hashElem(i)] = newBucket

print "[XYZ]: remove() i: ", i," hashElem[i]: ", hashElem(i), " hSet[hashElem(i): ", hSet[hashElem(i)]

def member(hSet,i):

return i in hSet[hashElem(i)]

def testOne():

s = create()

for i in range(40):

insert(s,i)

print "[XYZ]: S: ", s

insert(s,325)

insert(s,325)

insert(s,9898900067)

print "[XYZ]: S: ", s

print "[XYZ]: ,member(s,325): ",member(s,325)

remove(s,325)

print "[XYZ]: After Remove, member(s,325): ",member(s,325)

print "[XYZ]: member(s,9898900067)",member(s,9898900067)

testOne()

Write a program that asks the user to enter two dates (in YYYY-MM-DD format), and then prints which date is earlier. Your program should print an error message if the user enters an invalid date (like 2019-15-99).

Answers

Answer:

import java.util.*;

public class Dates {

   public static void main(String[] args) {

       String January,February, March, April, May, June, July,  

       August, September,October, November, December, month;

       January = February = March = April = May = June = July =  

               August = September = October = November = December = month = null;

       Scanner myScanner = new Scanner(System.in);  

       System.out.print("Enter date in the format mm/dd/yyyy: ");

       String input = myScanner.next();

       String months = input.substring(0,1);

       int monthInt = Integer.parseInt(months);

       if (monthInt == 01){

           month = January;

       }

       else if (monthInt == 02){

           month = February;

       }

       else if (monthInt == 03){

           month = March;

       }

       else if (monthInt == 04){

           month = April;

       }

       else if (monthInt == 05){

           month = May;

       }

       else if (monthInt == 06){

           month = June;

What are the final TTL and the destination IP enclosed in the set of IP datagrams when they arrive at the webserver www.? Does this webserver send a UDP segment or an ICMP message back to the host? What are the type and code enclosed in such UDP segment or ICMP message? What’s the source IP in the IP datagram carrying this UDP/ICMP packet? Whose IP is used as the destination IP for this UDP/ICMP packet? (hint: websever’s, my computer’s, router 147.153.69.30’s, or …?)

Answers

Answer:particular layer N, a PDU is a complete message that implements the protocol at that layer. However, when this “layer N PDU” is passed down to layer N-1, it becomes the data that the layer N-1 protocol is supposed to service. Thus, the layer N protocol data unit (PDU) is called the layer N-1 service data unit (SDU). The job of layer N-1 is to transport this SDU, which it does in turn by placing the layer N SDU into its own PDU format, preceding the SDU with its own headers and appending footers as necessary. This process is called data encapsulation, because the entire contents of the higher-layer message are encapsulated as the data payload of the message at the lower layer.

What does layer N-1 do with its PDU? It of course passes it down to the next lower layer, where it is treated as a layer N-2 SDU. Layer N-2 creates a layer N-2 PDU containing the layer N-1 SDU and layer N-2’s headers and footers. And the so the process continues, all the way down to the physical layer. In the theoretical model, what you end up with is a message at layer 1 that consists of application-layer data that is encapsulated with headers and/or footers from each of layers 7 through

Explanation:

What is the purpose of a Program Epic?

Answers

Answer:

An Epic is a container for a Solution development initiative large enough to require analysis, the definition of a Minimum Viable Product (MVP), and financial approval prior to implementation. Implementation occurs over multiple Program Increments (PIs) and follows the Lean startup 'build-measure-learn' cycle.

Explanation:

Hope this is what your looking for

The purpose of a Program Epic is to represent business capabilities that address various user needs.

What is Program Epic ?

An Epic is a holder for a Solution improvement drive sufficiently enormous to require examination, the meaning of a Minimum Viable Product (MVP), and monetary endorsement preceding execution. Execution happens over numerous Program Increments (PIs) and follows the Lean startup 'assemble measure-learn' cycle.

A program epic obliged to a solitary delivery train, conveyed by different groups, and crossing numerous PI emphases. Program Epics can address business abilities that address different client needs. Include: Functionality that meets explicit partner needs.

Thus, the purpose is explained.

Learn more about Program Epic

https://brainly.com/question/15450565

#SPJ2

Consider a set of mobile computing clients in a certain town who each
need to be connected to one of several possible base stations. We’ll
suppose there are n clients, with the position of each client specified
by its (x, y) coordinates in the plane. There are also k base stations; the
position of each of these is specified by (x, y) coordinates as well.
For each client, we wish to connect it to exactly one of the base
stations. Our choice of connections is constrained in the following ways.
There is a range parameter r—a client can only be connected to a base
station that is within distance r. There is also a load parameter L—no
more than L clients can be connected to any single base station.
Your goal is to design a polynomial-time algorithm for the following
problem. Given the positions of a set of clients and a set of base stations,
as well as the range and load parameters, decide whether every client can
be connected simultaneously to a base station, subject to the range and
load conditions in the previous paragraph

Answers

Answer: answer given in the explanation

Explanation:

We have n clients and k-base stations, say each client has to be connected to a base station that is located at a distance say 'r'. now the base stations doesn't have allocation for more than L clients.

To begin, let us produce a network which consists of edges and vertex

Network (N) = (V,E)

where V = [S, cl-l, - - - -  cl-n, bs-l - - - - - - bs-k, t]

given that cl-l, - - - - - cl-n represents nodes for the clients

also we have that bs-l, - - - - - bs-k represents the nodes for base station

Also

E = [ (s, cl-i), (cl-i,bs-j), (bs-j,t)]

(s, cl-i) = have capacity for all cl-i (clients)

(cl-i,bs-j) = have capacity for all cl-i  clients & bs-j (stations)

⇒ using Fond Fulkorson algorithm we  find the max flow in N

⇒ connecting cl-i clients to  bs-j stations

      like (cl-i, bs-j) = 1

   if f(cl-i, bs-j)  = 0

⇒ say any connection were to produce a valid flow, then

if cl-i (clients) connected                f(s,cl-i) = 1 (o otherwise)

if cl-i (clients) connected  to bs-j(stations)   f(cl-i,bs-j) = 1 (o otherwise)

   f(bs-j,t) = no of clients  (cl-i)  connected to bs-j

⇒ on each node, the max flow value (f) is longer than the no of clients that can be connected.

⇒ create the connection between the client and base station i.e. cl-l to base bs-j iff    f(cl-i, bs-j) = 1

⇒ when considering the capacity, we see that any client cannot directly connect to the base stations, and also the base stations cannot handle more than L clients, that is because the load allocated to the base statsion is L.

from this, we say f is the max no of clients (cl-i) that can be connected if we find the max flow, we can thus connect the client to the base stations easily.

cheers i hope this helps

numbers that the user inputs. You must use JoptionPane to input the three numbers. A first method must be called and used to develop logic to find the smallest of the three numbers. A second method must be used to print out that smallest number found.

Answers

Input the three numbers. A first method must be called and used to develop logic to find the smallest of the three numbers. A second method must be used to print out that smallest number found.

Explanation:

Input of 3 numbers.Then the numbers are checked to print the smallest one.

import java.util.Scanner;

public class Exercise1 {

public static void main(String[] args)

   {

       Scanner in = new Scanner(System.in);

       System.out.print("Input the first number: ");

       double x = in.nextDouble();

       System.out.print("Input the Second number: ");

       double y = in.nextDouble();

       System.out.print("Input the third number: ");

       double z = in.nextDouble();

       System.out.print("The smallest value is " + smallest(x, y, z)+"\n" );

   }

  public static double smallest(double x, double y, double z)

   {

       return Math.min(Math.min(x, y), z);

   }

}

Write the pseudocode for the following: A function called fahrenheitToCelsius that accepts a Real Fahrenheit temperature, performs the conversion, and returns the Real Celsius temperature. A function called celsiusToFahrenheit that accepts a Real Celsius temperature, performs the conversion, and returns the Real Fahrenheit temperature. A main module that asks user to enter a Fahrenheit temperature, calls the fahrenheitToCelsius function, and displays the Celsius temperature with a user-friendly message. It then asks the user to enter a Celsius temperature, calls the celsiusToFahrenheit function, and displays the Fahrenheit temperature with a user-friendly message.

Answers

Final answer:

The pseudocode provided defines two functions, fahrenheitToCelsius and celsiusToFahrenheit, which perform temperature conversions between Fahrenheit and Celsius, and a main module for user interaction to perform and display the conversions.

Explanation:

Here is the pseudocode for two temperature conversion functions and a main module to interact with the user.

Function: fahrenheitToCelsius

Input: Real fahrenheitTemperature
Output: Real celsiusTemperature
Begin
   Set celsiusTemperature to (fahrenheitTemperature - 32) * (5.0 / 9.0)
   Return celsiusTemperature
End

Function: celsiusToFahrenheit

Input: Real celsiusTemperature
Output: Real fahrenheitTemperature
Begin
   Set fahrenheitTemperature to (celsiusTemperature * (9.0 / 5.0)) + 32
Return fahrenheitTemperature
End

Main Module

Begin
   Display "Enter a Fahrenheit temperature: "
   Input fahrenheitTemperature
   Set celsiusTemperature to fahrenheitToCelsius(fahrenheitTemperature)
   Display "The equivalent Celsius temperature is: " + celsiusTemperature
   Display "Enter a Celsius temperature: "
  Input celsiusTemperature
   Set fahrenheitTemperature to celsiusToFahrenheit(celsiusTemperature)
   Display "The equivalent Fahrenheit temperature is: " + fahrenheitTemperature
End

Write the constructor for the Theater class. The constructor takes three int parameters, representing the number of seats per row, the number of tier 1 rows, and the number of tier 2 rows, respectively. The constructor initializes the theaterSeats instance variable so that it has the given number of seats per row and the given number of tier 1 and tier 2 rows and all seats are available and have the appropriate tier designation. Row 0 of the theaterSeats array represents the row closest to the stage. All tier 1 seats are closer to the stage than tier 2 seats. Complete the Theater constructor. /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier 2 Rows >= 0 */ public Theater(int seatsPerRow, int tier1Rows, int tier 2 Rows)

Answers

Answer:

See explaination

Explanation:

class Seat {

private boolean available;

private int tier;

public Seat(boolean isAvail, int tierNum)

{ available = isAvail;

tier = tierNum; }

public boolean isAvailable() { return available; }

public int getTier() { return tier; }

public void setAvailability(boolean isAvail) { available = isAvail; } }

//The Theater class represents a theater of seats. The number of seats per row and the number of tier 1 and tier 2 rows are

//determined by the parameters of the Theater constructor.

//Row 0 of the theaterSeats array represents the row closest to the stage.

public class Theater {

private Seat[][] theaterSeats; /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier2Rows >= 0 */

public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) {

theaterSeats= new Seat[tier1Rows+tier2Rows][seatsPerRow];

}

public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) {

if(theaterSeats[toRow][toCol].isAvailable()) {

int tierDestination =theaterSeats[toRow][toCol].getTier();

int tierSource =theaterSeats[fromRow][fromCol].getTier();

if(tierDestination<=tierSource) {

if(tierDestination==tierSource) {

if(fromRow<toRow) {

return false;

}else {

theaterSeats[toRow][toCol].setAvailability(false);

theaterSeats[fromRow][fromCol].setAvailability(true);

return true;

}

}

theaterSeats[toRow][toCol].setAvailability(false);

theaterSeats[fromRow][fromCol].setAvailability(true);

return true;

}else {

return false;

}

}else {

return false;

}

}

public static void main(String[] args) {

//Lets understand it with simple example

Theater t1 = new Theater(3,1,2);

//Our threater has 3 seat in each row and we have one tier 1 row and 1 tier 2 row

//total no of seat will be 9.

//Lets create our seat

t1.theaterSeats[0][0] = new Seat(true,1);

t1.theaterSeats[0][1] = new Seat(false,1);

t1.theaterSeats[0][2] = new Seat(true,1);

t1.theaterSeats[1][0] = new Seat(true,2);

t1.theaterSeats[1][1] = new Seat(true,2);

t1.theaterSeats[1][2] = new Seat(true,2);

t1.theaterSeats[2][0] = new Seat(false,2);

t1.theaterSeats[2][1] = new Seat(false,2);

t1.theaterSeats[2][2] = new Seat(true,2);

//Lets print out theater and see which seat is available or which is not

System.out.println("Theater===>");

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

System.out.print("["+i+"]"+"["+j+"] : "+t1.theaterSeats[i][j].isAvailable()+" ");

}

System.out.println();

}

System.out.println("(2,1) want to change seat to (0,0)");

System.out.println("["+2+"]"+"["+1+"]"+"===>"+"["+0+"]"+"["+0+"]");

t1.reassignSeat(2, 1, 0, 0);

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

System.out.print("["+i+"]"+"["+j+"] : "+t1.theaterSeats[i][j].isAvailable()+" ");

}

System.out.println();

}

}

}

Using the world_x database you installed in Module 1, list the countries and the capitals of each country. Modify your query to limit the list to those countries where less than 30% of the population speaks English. Be sure to identify the literary sources you used to look up any SQL syntax you used to formulate your query. Submit your query and query results Word file.

Answers

Answer:

SELECT country.Name, city.Name

FROM country

JOIN countrylanguage ON country.Code = countrylanguage.CountryCode

JOIN city ON country.Capital = city.ID

WHERE countrylanguage.Language = 'English'

AND countrylanguage.Percentage < 30;

Explanation:

SELECT is used to query the database and get back the specified fields.

City.Name is an attribute of city table.

country.Name is an attribute of country table.

FROM is used to query the database and get back the preferred information by specifying the table name.

country , countrylanguage and city are the table names.

country and countrylanguage are joined based ON country.Code = countrylanguage.CountryCode

countrylanguage and city are joined based ON country.Capital = city.ID

WHERE is used to specify a condition based on which the data is to be retrieved. The conditions are as follows:

countrylanguage.Language = 'English'

countrylanguage.Percentage < 30;

Write a program that converts a temperature from Celsius to Fahrenheit. It should (1) prompt the user for input, (2) read a double value from the keyboard, (3) calculate the result, and (4) format the output to one decimal place. For example, it should display "24.0 C = 75.2 F". Here is the formula. Be careful not to use integer division! F = C × 9 5 + 32

Answers

Answer:

celsius = float(input("Enter the celcius value: "))

f = 1.8 * celsius + 32

print(str(celsius) + " C = "+ str(f) + " F")

Explanation:

The code is in Python.

Ask the user for the input, celsius value

Convert the celsius value to fahrenheit using the given formula

Print the result as in shown in the example output

Answer:

See explaination

Explanation:

#include<iostream>

#include<iomanip>

using namespace std;

int main(){

double tempF, tempC;

cout<<"Enter a degree in Celsius: ";

cin>>tempC;

tempF = tempC*(9/5.0)+32;

cout<<setprecision(1)<<fixed;

cout<<tempC<<" C = "<<tempF<<" F"<<endl;

return 0;

}

Write a program to simulate the design process of the course. First, create a struct for the course which consists of following members: course number (int type, e.g. 1200), course start date (int type, e.g. 20200107), course hours (int type, how many hours per week) and lecturer ID (int type). Second, create a struct for lecturer, which has following members: lecturer ID (int type), lecturer office hours (int type, how many office hours per week) and course teaching(array[int] type). Third, create a struct for student, which as following members: student ID (int type), course taken (array[int type). Then answer following questions 1, 2 and 3 based on these structures: 1. The department decide to offer three courses in a semester: 1000, 1100 and 1200. Please create these courses with structs you defined above. Their information is given below: Course number Course start date Course hours Lecturer ID 1000 20200107 2 100 1100 20200113 4 200 1200 20200203 4 100 2. Department also assigned two lecturers to teach these courses. Please create documents for lecturers and print out the information for both lectures on the screen. Note: Each lecturer will be assigned 2 hours office hours for each course he/she teaches. 3. A student, whose ID is 2000, are considering taking 2 courses among above courses. Please print out how many course hours he/she needs to take each week. Note, simply add up the course hours from table in question 1 will not be considered as correct answer. Your program should first ask this student to input the course number he/she registered, then print the total course hours. 4. Conduct an experiment with Arduino using an Angle Rotary Sensor and a Servo (connect sensors to Arduino appropriately). The Angle Rotary Sensor must control the movement of the Servo. In other words, when you change the angle of the Rotary Angle Sensor (0 to 300 degrees), the Servo will rotate the short white blade accordingly after mapping the Angle Rotary Sensor value (0 to 300 to a Servo position (0 to 180). Also, display the angle degree of the Angle Rotary Sensor and the position of the Servo on the Serial Monitor window. Use Serial.print function to print on the Serial Monitor window, which can be open by clicking on the icon- on the upper right area of the Arduino window. Also, you need to use the following statement in the setup function: Serial.begin(9600);

Answers

Answer:

#include <iostream>

using namespace std;

struct Course

{

int courseNumber;

int courseStartDate;

int courseHours;

int lecturerId;

};

struct Lecturer

{

int lecturerId;

int officeHours;

Course courseTeaching[2];

};

struct Student

{

int studentId;

Course coursesTaken[2];

};

int main()

{

Course courseObj1, courseObj2, courseObj3;

courseObj1.courseNumber = 1000;

courseObj1.courseStartDate = 20200107;

courseObj1.courseHours = 2;

courseObj1.lecturerId = 100;

courseObj2.courseNumber = 1100;  

courseObj2.courseStartDate = 20200113;

courseObj2.courseHours = 4;

courseObj2.lecturerId = 200;

courseObj3.courseNumber = 1200;

courseObj3.courseStartDate = 20200203;

courseObj3.courseHours = 4;

courseObj3.lecturerId = 100;

Lecturer lecturerObj1, lecturerObj2;

lecturerObj1.lecturerId = 100;

lecturerObj1.officeHours = 2;

lecturerObj1.courseTeaching[0] = courseObj1;

lecturerObj1.courseTeaching[1] = courseObj3;

lecturerObj2.lecturerId = 200;

lecturerObj2.officeHours = 2;

lecturerObj2.courseTeaching[0] = courseObj2;

Student student;

student.studentId = 2000;

student.coursesTaken[0] = courseObj1;

student.coursesTaken[1] = courseObj3;

cout << "1. Lecturer ID: " << lecturerObj1.lecturerId << "\tOffice Hours: " << lecturerObj1.officeHours << endl;

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

cout << "COURSE " << (i + 1) << ":\n---------\n" << "Course Number: " << lecturerObj1.courseTeaching[i].courseNumber << endl << "Course start date: " << lecturerObj1.courseTeaching[i].courseStartDate << endl << "Course hours: " << lecturerObj1.courseTeaching[i].courseHours << endl << "Lecturer ID: " << lecturerObj1.courseTeaching[i].lecturerId << endl;

cout << "\n2. Lecturer ID: " << lecturerObj2.lecturerId << "\tOffice Hours: " << lecturerObj2.officeHours << endl;

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

cout << "COURSE " << (i + 1) << ":\n---------\n" << "Course Number: " << lecturerObj2.courseTeaching[i].courseNumber << endl << "Course start date: " << lecturerObj2.courseTeaching[i].courseStartDate << endl << "Course hours: " << lecturerObj2.courseTeaching[i].courseHours << endl << "Lecturer ID: " << lecturerObj2.courseTeaching[i].lecturerId << endl;

int courseNumber;

cout << "\n Enter the course number: ";

cin >> courseNumber;

int index = -1;

int len = sizeof(student.coursesTaken) / sizeof(student.coursesTaken[0]);

int totalHours = 0;

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

{

if(student.coursesTaken[i].courseNumber == courseNumber)

{

totalHours += student.coursesTaken[i].courseHours;

}

}

if(totalHours == 0)

cout << "\n Student is not registered to this course!\n";

else

cout << "\nStudent " << student.studentId << " needs " << totalHours << " hours per week of this course.\n";

return 0;

}

Explanation:

Create the 3 objects of Course class and set their properties respectively.Create the 2 objects of Lecturer class and set their properties respectively.Create an object of Student class and set their properties respectively.Run a for loop and check whether the current courseNumber is already added and then increment the total number of hours for that course.Finally check if totalHours is equal to 0 or not and then display the suitable message accordingly.
Other Questions
Look at the timeline.A timeline. In 1712, Thomas Newcomen invents the first steam engine. In 1973, Eli Whitney invents the cotton gin. In 1837, Samuel Morse invents the American telegraph. In 1877, Thomas Edison invents the phonograph.What would be the best title for this timeline? The attractiveness test for evaluating whether diversification into a particular industry is likely to build shareholder value involves determining whether A. E) there are attractive strategic fits between the value chains of the company's present businesses and the value chain of the new business it is considering entering. B. B) the potential diversification move will boost the company's competitive advantage in its existing business. C. A) conditions in the target industry allow for profits and return on investment that is equal to or better than that of the company's present business(es). D. D) key success factors in the target industry are attractive. E. C) shareholders will view the contemplated diversification move as attractive. Construct a 95% confidence interval for the population mean, mu. Assume the population has a normal distribution. A random sample of 16 lithium batteries has a mean life of 645 hours with a standard deviation of 31 hours. Round to the nearest tenth. Thanks to his firm's decentralization and use of responsibility accounting, Matt has more time to review a proposed new joint venture with one of the firm's business partners. What advantage of decentralization does this illustrate? Your friend says the new restaurant in town has the best hamburgers. To see whether she is correct, you read a variety of online restaurant reviews. You are using ________ reasoning to determine whether this conclusion is valid. What would be the most likely effect on the transcription of the trp structural genes for the mutation scenarios provided? mutation that prevents ribosome binding to the mRNA 5' UTR mutation that changes region 1 tryptophan codons into alanine codons mutation that creates a stop codon in region 1 of mRNA 5' UTR deletions in region 2 of the mRNA 5' UTR deletions in region 3 of the mRNA 5' UTR deletions in region 4 of the mRNA 5' UTR deletion of the string of adenine after region 4 of the mRNA 5' UTR When does a student need to file the FAFSA?A. at the beginning of the courseB. after every semesterC. at the end of the courseD. every year of college attendance Which of these is a problem with using nuclear energy?A.It is very expensive to use.B.It is a non-renewable energy source.C.There aren't enough qualified technicians.D.We don't have a way to contain the radioactive waste produced. The writer of the excerpt uses Farah suffers major brain trauma in a train crash. As a result, she can no longer form new memories. She can recall the memories of her life before the crash quite accurately, but she cannot remember any new people she meets or any experiences she has afterward. Farah's condition is known as The phrase "God, Gold, and Glory" is often used to describe...motivations for European exploration and colonizationthe impact that American Indian cultures had on Europeansthe spread of Baptist and Methodist churches in Georgiathe removal of American Indians from Georgia On October 10, the stockholders equity of Sherman Systems appears as follows. Common stock$10 par value, 77,000 shares authorized, issued, and outstanding $ 770,000 Paid-in capital in excess of par value, common stock 241,000 Retained earnings 904,000 Total stockholders equity $ 1,915,000 1. Prepare journal entries to record the following transactions for Sherman Systems. Purchased 5,500 shares of its own common stock at $30 per share on October 11. Sold 1,125 treasury shares on November 1 for $36 cash per share. Sold all remaining treasury shares on November 25 for $25 cash per share. 2. Prepare the stockholders' equity section after the October 11 treasury stock purchase. What is transition metals oxidation state? there are 390 students at a school if each classroom holds 30 students how many classroom are needed at the school? what is one benefit of lifelong physical activity? The area of one of the small right triangles outlined in blue is A cm2, while the area of the square outlined in red is B cm2. Which expressions show the area of the shaded region in terms of A and B? Check all that apply.4A + B8A + B2A + B1.5B12A Which legendary painters is known by his first name? Aluminium reacts with chloride to produce aluminium chloride if you begin with 3.2g of aluminium and 5.4g of chloride which is the limiting reactant and how many grams of aluminium chloride can be produced from the amount of limiting reactant available Seniors Trinity and Jordan tease each other and send each other funny text messages. Jordon tells Trinity she is beautiful and asks her to meet him after school. Trinity is surprised when Jordan immediately pushes her up against a wall, touches her body, and does not stop when she tells him to. The two major processes involved in the carbon cycle are