In this puzzle you have a list of n pitchers, with known capacities, c1, c2, ... cn, of holding water in gallons. You have a faucet that can be used as often and as much as the player needs. The goal is to measure exactly g gallons of water, using nothing other than these pitchers. Suppose the current amounts of water that these pitchers hold is w1, w2, ... wn,. These numbers are assumed to be 0 initially. The puzzle is solved as soon as wi = g for any i. A player can perform the following operations:

 Fill pitcher i (from the faucet). The precondition of this operation is: ci > wi ≥ 0. The effect is: wi = ci.

 Empty pitcher i. The precondition of this operation is: ci ≥ wi > 0. The effect is: wi = 0.

 Pour pitcher i to pitcher j. The precondition of this operation is: (ci ≥ wi > 0) and (cj > wj ≥ 0). In words, pitcher i must have some water to pour, and pitcher j must have some unused capacity to receive it. The (partial) effect is: (wi = 0) or (wj = cj) or both. In words, the pour operation must continue until pitcher i becomes empty (and its content is added to pitcher j's content), or pitcher j becomes full (and pitcher i retains the remainder), whichever occurs first. They may occur simultaneously.

A Sample Run

Select the puzzle to solve:

1. Pitchers

2. Eight puzzle

Your selection: 1

Enter the number of pitchers: 3

Enter the capacities of the 3 pitchers (gallons): 2, 5, 10

Enter the goal (gallons): 1

Current configuration: [0, 0, 0]

Please select your next move from the following choices:

1. Fill pitcher 1

2. Fill pitcher 2

3. Fill pitcher 3

Your selection: 2

Current configuration: [0, 5, 0]

Please select your next move from the following choices:

1. Fill pitcher 1

2. Fill pitcher 3

3. Empty pitcher 2

4. Pour pitcher 2 to 1

5. Pour pitcher 2 to 3

Your selection: 4

Current configuration: [2, 3, 0]

Please select your next move from the following choices:

1. Fill pitcher 2

2. Fill pitcher 3

3. Empty pitcher 1

4. Empty pitcher 2

5. Pour pitcher 1 to 2

6. Pour pitcher 1 to 3

7. Pour pitcher 2 to 3

Your selection: 3 Current configuration: [0, 3, 0]

Please select your next move from the following choices:

1. Fill pitcher 1

2. Fill pitcher 2

3. Fill pitcher 3

4. Empty pitcher 2

5. Pour pitcher 2 to 1

6. Pour pitcher 2 to 3

Your selection: 5 Current configuration: [2, 1, 0]

Great! You have reached the goal in 4 moves. Bye.

Answers

Answer 1

Answer:

See explaination

Explanation:

#include <iostream>

#include <vector>

using namespace std;

// function to print configuration for each pitcher

void printConfig(vector<int> w, int n)

{

cout << "Current configuration: [" << w[0];

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

{

cout << ", " << w[i];

}

cout << "]" << endl;

}

void getOptions(vector<int> c, vector<int> w, int n, vector<pair<int, pair<int, int>>> &options)

{

// options count

int count = 0;

// fill

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

{

if(c[i] > w[i] && w[i] >= 0)

{

count ++;

cout << count << ". Fill pitcher " << (i+1) << endl;

// add options to list

options.push_back(make_pair(1, make_pair(i, 0)));

}

}

// empty

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

{

if(c[i] >= w[i] && w[i] > 0)

{

count++;

cout << count << ". Empty pitcher " << (i+1) << endl;

// add options to list

options.push_back(make_pair(2, make_pair(i, 0)));

}

}

// Pour pitcher i to pitcher j

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

{

if(c[i] >= w[i] && w[i] > 0)

{

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

{

if(i!=j && c[j] > w[j] && w[j] >= 0)

{

count++;

cout << count << ". Pour pitcher " << (i+1) << " to " << (j+1) << endl;

// add options to list

options.push_back(make_pair(3, make_pair(i, j)));

}

}

}

}

}

void execute(vector<int> c, vector<int> &w, pair<int, pair<int, int>> option)

{

int i = option.second.first;

// for fill

if(option.first == 1)

{

w[i] = c[i];

}

// empty

else if(option.first == 2)

{

w[i] = 0;

}

// pour

else

{

int j = option.second.second;

if(w[i] >= c[j])

{

w[i] = w[i] - c[j];

w[j] = c[j];

}

else

{

w[j] = w[i];

w[i] = 0;

}

}

}

int main()

{

// required variables

int choice, n, temp, g, flag, moves = 0;

// vectors are dynamic sized arrays

vector<int> c, w;

vector<pair<int, pair<int, int>>> options;

// select puzzle

cout << "Select the puzzle to solve:\n";

cout << "1. Pitchers\n";

cout << "2. Eight puzzle\n";

cout << "Your selection: ";

cin >> choice;

if(choice == 1)

{

// input values required

cout << "Enter the number of pitchers: ";

cin >> n;

// array for pitchers

cout << "Enter the capacities of the " << n << " pitchers (gallons): ";

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

{

cin >> temp;

c.push_back(temp);

w.push_back(0);

}

cout << "Enter the goal (gallons): ";

cin >> g;

// start game

while(true)

{

// print configuration

printConfig(w, n);

// check for goal state

flag = 0;

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

{

if(w[i] == g)

{

flag = 1;

break;

}

}

if(flag)

{

cout << "Great! You have reached the goal in " << moves << " moves. Bye." << endl;

break;

}

// get and print options

//empty previous options

options.clear();

getOptions(c, w, n, options);

// ask for user's selection

cout << "Your selection: ";

cin >> choice;

// update moves

moves++;

// perform according to the selection

execute(c, w, options[choice-1]);

}

}

return 0;

}


Related Questions

Write the method addItemToStock to add an item into the grocery stock array. The method will: • Insert the item with itemName add quantity items to stock. • If itemName is already present in stock, increase the quantity of the item, otherwise add new itemName to stock. • If itemName is not present in stock, insert at the first null position in the stock array. After the insertion all items are adjacent in the array (no null positions between two items). • Additionally, double the capacity of the stock array if itemName is a new item to be inserted and the stock is full.

Answers

Answer:

#include <stdio.h>

#include <iostream>

using namespace std;

int main()

{

   //varible to indicate size of the array

   int size=20;

   //arrays to hold grocery item names and their quantities

   std::string grocery_item[size];

   int item_stock[size];

   //variables to hold user input

   std::string itemName;

   int quantity;

   //variable to check if item is already present

   bool itemPresent=false;

   //variable holding full stock value

   int full_stock=100;

   for(int n=0; n<size; n++)

   {

       grocery_item[n]="";

       item_stock[n]=0;

   }

   do

   {

       std::cout << endl<<"Enter the grocery item to be added(enter q to quit): ";

       cin>>itemName;

       if(itemName=="q")

       {

               cout<<"Program ends..."<<endl; break;

       }

       else

       {

           std::cout << "Enter the grocery item stock to be added: ";

           cin>>quantity;

       }

   for(int n=0; n<size; n++)

   {

       if(grocery_item[n]==itemName)

       {

           itemPresent=true;

           item_stock[n]=item_stock[n]+quantity;

       }

   }

   if(itemPresent==false)

   {

       for(int n=0; n<size; n++)

       {

           if(grocery_item[n]=="")

           {

               itemPresent=true;

               grocery_item[n]=itemName;

               item_stock[n]=item_stock[n]+quantity;

           }

       

           if(item_stock[n]==full_stock)

           {

               item_stock[n]=item_stock[n]*2;

           }

       }

   }

   }while(itemName!="q");

   return 0;

}

OUTPUT

Enter the grocery item to be added(enter q to quit): rice

Enter the grocery item stock to be added: 23

Enter the grocery item to be added(enter q to quit): bread

Enter the grocery item stock to be added: 10

Enter the grocery item to be added(enter q to quit): bread

Enter the grocery item stock to be added: 12

Enter the grocery item to be added(enter q to quit): q

Program ends...

Explanation:

1. The length of the array and the level of full stock has been defined inside the program.

2. Program can be tested for varying values of length of array and full stock level.

3. The variables are declared outside the do-while loop.

4. Inside do-while loop, user input is taken. The loop runs until user opts to quit the program.

5. Inside do-while loop, the logic for adding the item to the array and adding the quantity to the stock has been included. For loops have been used for arrays.

6. The program only takes user input for the item and the respective quantity to be added.


3.34 LAB: Mad Lib - loops in C++

Mad Libs are activities that have a person provide various words, which are then used to complete a short story in unexpected (and hopefully funny) ways.

Write a program that takes a string and integer as input, and outputs a sentence using those items as below. The program repeats until the input is quit 0.

Ex: If the input is:
apples 5
shoes 2
quit 0

the output is:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.

Make sure your answer is in C++.

Answers

Answer:

A Program was written to carry out some set activities. below is the code program in C++ in the explanation section

Explanation:

Solution

CODE

#include <iostream>

using namespace std;

int main() {

string name; // variables

int number;

cin >> name >> number; // taking user input

while(number != 0)

{

// printing output

cout << "Eating " << number << " " << name << " a day keeps the doctor away." << endl;

// taking user input again

cin >> name >> number;

}

}

Note: Kindly find an attached copy of the compiled program output to this question.

In this exercise we have to use the knowledge in computational language in C++ to describe a code that best suits, so we have:

The code can be found in the attached image.

What is looping in programming?

In a very summarized way, we can describe the loop or looping in software as an instruction that keeps repeating itself until a certain condition is met.

To make it simpler we can write this code as:

#include <iostream>

using namespace std;

int main() {

string name; // variables

int number;

cin >> name >> number; // taking user input

while(number != 0)

{

// printing output

cout << "Eating " << number << " " << name << " a day keeps the doctor away." << endl;

// taking user input again

cin >> name >> number;

}

}

See more about C++ at brainly.com/question/19705654

Write an expression to detect that the first character of userinput matches firstLetter.

import java.util.Scanner; public class CharMatching { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userInput; char firstLetter; userInput = scnr.nextLine(); firstLetter = scnr.nextLine().charAt(0); if (/* Your solution goes here */) { System.out.println("Found match: " + firstLetter); } else { System.out.println("No match: " + firstLetter); } return; } }

Answers

Answer: Provided in the explanation segment

Explanation:

Below is the code to run this program.

we have that the

Program

import java.util.Scanner;

public class CharMatching {

  public static void main(String[] args) {

      //Scanner object for keyboard read

      Scanner scnr=new Scanner(System.in);

      //Variable for user input string

      String userInput;

      //Variable for firstletter input

      char firstLetter;

      //Read user input string

      userInput=scnr.nextLine();

      //Read first letter from user

      firstLetter=scnr.nextLine().charAt(0);

      //Comparison without case sensititvity and result

      if(Character.toUpperCase(firstLetter)==Character.toUpperCase(userInput.charAt(0))) {

          System.out.println("Found match: "+firstLetter);

      }

      else {

          System.out.println("No match: "+firstLetter);

      }

  }

}

Output

Hello

h

Found match: h

cheers i hope this helped !!!

Which of the following is an example of the rewards & consequences characteristic of an organization?
OOO
pay raise
time sheets
pay check
pay scale

Answers

Answer:

Pay raise is an example of the rewards & consequences characteristic of an organization.

I think its pay rase?

Box one:
logical
Date and time
Compatibility
Web

Box 2:
&
$
=
#

Box 3:
Not
If
Or
Sum

Answers

Box One is logical
Box Two I’m not sure, it depends on what language or program or website you’re using, however I’d assume it would be ‘=‘
Box Three is If

3.15 LAB: Countdown until matching digits
Write a program that takes in an integer in the range 20-98 as input. The output is a countdown starting from the integer, and stopping when both output digits are identical.

Ex: If the input is:

93
the output is:

93 92 91 90 89 88
Ex: If the input is:

77
the output is:

77
Ex: If the input is:

15
or any value not between 20 and 98 (inclusive), the output is:

Input must be 20-98.


#include

using namespace std;

int main() {

// variable

int num;



// read number

cin >> num;

while(num<20||num>98)

{

cout<<"Input must be 20-98 ";

cin>> num;

}



while(num % 10 != num /10)

{

// print numbers.

cout<
// update num.

num--;

}

// display the number.

cout<
return 0;

}




I keep getting Program generated too much output.
Output restricted to 50000 characters.

Check program for any unterminated loops generating output

Answers

Answer:

See explaination

Explanation:

n = int(input())

if 20 <= n <= 98:

while n % 11 != 0: // for all numbers in range (20-98) all the identical

digit numbers are divisible by 11,So all numbers that

​​​​​​ are not divisible by 11 are a part of count down, This

while loop stops when output digits get identical.

print(n, end=" ")

n = n - 1

print(n)

else:

print("Input must be 20-98")

How we can earn from an app​

Answers

Answer:

Hewo, Here are some ways in which apps earn money :-

AdvertisementSubscriptionsIn-App purchasesMerchandisePhysical purchasesSponsorship

hope it helps!

For dinner, a restaurant allows you to choose either Menu Option A: five appetizers and three main dishes or Menu Option B: three appetizers and four main dishes. There are six kinds of appetizer on the menu and five kinds of main dish.

How many ways are there to select your menu, if...

a. You may not select the same kind of appetizer or main dish more than once.
b. You may select the same kind of appetizer and/or main dish more than once.
c. You may select the same kind of appetizer or main dish more than once, but not for all your choices, For example in Menu Option A, it would be OK to select four portions of 'oysters' and one portion of 'pot stickers', but not to select all five portions of 'oysters'.)

In each case show which formula or method you used to derive the result.

Answers

Answer:

The formula used in this question is called the probability of combinations or combination formula.

Explanation:

Solution

Given that:

Formula applied is stated as follows:

nCr = no of ways to choose r objects from n objects

  = n!/(r!*(n-r)!)

The Data given :

Menu A : 5 appetizers and 3 main dishes

Menu B : 3 appetizers and 4 main dishes

Total appetizers - 6

Total main dishes - 5

Now,

Part A :

Total ways = No of ways to select menu A + no of ways to select menu B

          = (no of ways to select appetizers in A)*(no of ways to select main dish in A) + (no of ways to select appetizers in B)*(no of ways to select main dish in B)

          = 6C5*5C3 + 6C3*5C4

          = 6*10 + 20*5

          = 160

Part B :

Since, we can select the same number of appetizers/main dish again so the number of ways to select appetizers/main dishes will be = (total appetizers/main dishes)^(no of appetizers/main dishes to be selected)

Total ways = No of ways to select menu A + no of ways to select menu B  

          = (no of ways to select appetizers in A)*(no of ways to select main dish in A) + (no of ways to select appetizers in B)*(no of ways to select main dish in B)

          = (6^5)*(5^3) + (6^3)*(5^4)

          = 7776*125 + 216*625

          = 1107000

Part C :

No of ways to select same appetizers and main dish for all the options

= No of ways to select menu A + no of ways to select menu B  

= (no of ways to select appetizers in A)*(no of ways to select main dish in A) + (no of ways to select appetizers in B)*(no of ways to select main dish in B)

=(6*5) + (6*5)

= 60

Total ways = Part B - (same appetizers and main dish selected)      

= 1107000 - 60

= 1106940

In this lab, you use the flowchart and pseudocode found in the figures below to add code to a partially created C++ program. When completed, college admissions officers should be able to use the C++ program to determine whether to accept or reject a student, based on his or her test score and class rank.

// HouseSign.cpp - This program calculates prices for custom made signs.

#include
#include
using namespace std;
int main()
{
// This is the work done in the housekeeping() function
// Declare and initialize variables here
// Charge for this sign
// Color of characters in sign
// Number of characters in sign
// Type of wood

// This is the work done in the detailLoop() function
// Write assignment and if statements here

// This is the work done in the endOfJob() function
// Output charge for this sign
cout << "The charge for this sign is $" << charge << endl;
return(0);
}

Answers

Here is the complete question.

In this lab, you use the flowchart and pseudocode found in the figures below to add code to a partially created C++ program. When completed, college admissions officers should be able to use the C++ program to determine whether to accept or reject a student, based on his or her test score and class rank.

start input testScore,

classRank if testScore >= 90 then if classRank >= 25 then output "Accept"

else output "Reject" endif else if testScore >= 80

then if classRank >= 50 then output "Accept" else output "Reject" endif

else if testScore >= 70

then if classRank >= 75 then output "Accept"

else output "Reject"

endif else output "Reject"

endif

endif

endif

stop

Study the pseudocode in picture above. Write the interactive input statements to retrieve: A student’s test score (testScore) A student's class rank (classRank) The rest of the program is written for you. Execute the program by clicking "Run Code." Enter 87 for the test score and 60 for the class rank. Execute the program by entering 60 for the test score and 87 for the class rank.

[comment]: <> (3. Write the statements to convert the string representation of a student’s test score and class rank to the integer data type (testScore and classRank, respectively).)

Function: This program determines if a student will be admitted or rejected. Input: Interactive Output: Accept or Reject

*/ #include using namespace std; int main() { // Declare variables

// Prompt for and get user input

// Test using admission requirements and print Accept or Reject

if(testScore >= 90)

{ if(classRank >= 25)

{ cout << "Accept" << endl; }

else

cout << "Reject" << endl; }

else { if(testScore >= 80)

{ if(classRank >= 50)

cout << "Accept" << endl;

else cout << "Reject" << endl; }

else { if(testScore >= 70)

{ if(classRank >=75) cout << "Accept" << endl;

else cout << "Reject" << endl; }

else cout << "Reject" << endl; } } } //End of main() function

Answer:

Explanation:

The objective here is to use the flowchart and pseudocode found in the figures below to add code to a partially created C++ program. When completed, college admissions officers should be able to use the C++ program to determine whether to accept or reject a student, based on his or her test score and class rank.

PROGRAM:

#include<iostream>

using namespace std;

int main(){

// Declare variables

int testScore, classRank;

// Prompt for and get user input

cout<<"Enter test score: ";

cin>>testScore;

cout<<"Enter class rank: ";

cin>>classRank;

// Test using admission requirements and print Accept or Reject

if(testScore >= 90)  

{ if(classRank >= 25)

{ cout << "Accept" << endl; }

else

cout << "Reject" << endl;

}

else { if(testScore >= 80)

{ if(classRank >= 50)

cout << "Accept" << endl;

else cout << "Reject" << endl; }

else { if(testScore >= 70)

{ if(classRank >=75) cout << "Accept" << endl;

else cout << "Reject" << endl;

}

else cout << "Reject" << endl; }

}

return 0;

} //End of main() function

OUTPUT:

See the attached file below:

Define a function CoordTransform() that transforms the function's first two input parameters xVal and yVal into two output parameters xValNew and yValNew. The function returns void. The transformation is new = (old + 1) * 2. Ex: If xVal = 3 and yVal = 4, then xValNew is 8 and yValNew is 10.

Answers

Answer:

Check the explanation

Explanation:

#include <iostream>

using namespace std;

void CoordTransform(int x, int y, int& xValNew,int& yValNew){

  xValNew = (x+1)*2;

  yValNew = (y+1)*2;

}

int main() {

  int xValNew = 0;

  int yValNew = 0;

  CoordTransform(3, 4, xValNew, yValNew);

  cout << "(3, 4) becomes " << "(" << xValNew << ", " << yValNew << ")" << endl;

  return 0;

}

Write the interface (.h file) of a class Counter containing: A data member counter of type int. A data member named counterID of type int. A static int data member named nCounters. A constructor that takes an int argument. A function called increment that accepts no parameters and returns no value. A function called decrement that accepts no parameters and returns no value. A function called getValue that accepts no parameters and returns an int. A function named getCounterID that accepts no parameters and returns an int.

Answers

Explanation:

See the attached image for The interface (.h file) of a class Counter

Implement the function pairSum that takes as parameters a list of distinct integers and a target value n and prints the indices of all pairs of values in the list that sum up to n. If there are no pairs that sum up to n, the function should not print anything. Note that the function does not duplicate pairs of indices

Answers

Answer:

Following are the code to this question:

def pairSum(a,x): #find size of list

   s=len(a) # use length function to calculte length of list and store in s variable

   for x1 in range(0, s):  #outer loop to count all list value

       for x2 in range(x1+1, s):    #inner loop

           if a[x1] + a[x2] == x:    #condition check

               print(x1," ",x2) #print value of loop x1 and x2  

pairSum([12,7,8,6,1,13],13) #calling pairSum method

Output:

0   4

1   3

Explanation:

Description of the above python can be described as follows:

In the above code, a method pairSum is declared, which accepts two-parameter, which is "a and x". Inside the method "s" variable is declared that uses the "len" method, which stores the length of "a" in the "s" variable. In the next line, two for loop is declared, in the first loop, it counts all variable position, inside the loop another loop is used that calculates the next value and inside a condition is defined, that matches list and x variable value. if the condition is true it will print loop value.

g Q 2 Suppose I need a data structure having the following characteristics: a) must be very space efficient, and b) I have a good idea of how much total data needs to be stored. b) must have fastest access possible, and c) once I add an item to the data structure, I do not remove it. Part 1: What data structure would I choose and why? (2,4) Part 2: If I remove characteristic b, what similar data structure is a possible candidate?

Answers

Explanation:

a.I would choose an advanced data structure like  dispersion tables.

Scatter tables, better known as hash tables, are one of the most frequently used data structures. To get an initial idea, scatter tables make it possible to have a structure that relates a key to a value, such as a dictionary. Internally, the scatter tables are an array. Each of the array positions can contain none, one or more dictionary entries.

It will normally contain a maximum of one, which allows quick access to the elements, avoiding a search in most cases. To know at which position in the array to search or insert a key, a scatter function is used. A scatter function relates each key to an integer value. Two equal keys must have the same dispersion value, also called a hash value, but two different keys can have the same dispersion value, which would cause a collision.

B. If I eliminated the characteristic b, a possible candidate keeping the previous characteristics would be: Balanced binary trees

Balanced binary trees are data structures that store key-data pairs, in an orderly way according to the keys, and allow quick access to the data, given a particular key, and to go through all the elements in order.

They are appropriate for large amounts of information and have less overhead than a scatter table, although the access time is of greater computational complexity.

Although the storage form has a tree structure internally, this is not externalized in the API, making the handling of the data transparent. They are called balanced because, each time they are modified, the branches are rebalanced in such a way that the height of the tree is as low as possible, thus shortening the average time of access to the data.

Write a static method named contains that accepts two arrays of integers a1 and a2 as
parameters and that returns a boolean value indicating whether or not a2's sequence of
elements appears in a1 (true for yes, false for no). The sequence of elements in a2 may
appear anywhere in a1 but must appear consecutively and in the same order. For example, if
variables called list1 and list2 store the following values:

int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
int[] list2 = {1, 2, 1};

Then the call of contains(list1, list2) should return true because list2's sequence of
values {1, 2, 1} is contained in list1 starting at index 5. If list2 had stored the values {2,
1, 2}, the call of contains(list1, list2) would return false because list1 does not
contain that sequence of values. Any two lists with identical elements are considered to contain
each other, so a call such as contains(list1, list1) should return true.

Answers

Answer:

Sew explaination foe code

Explanation:

import java.lang.*;

import java.util.*;

import java.io.*;

class Main

{

public static Boolean checkSubset(int[] list1, int[] list2)

{

int l = list2.length;

for(int i = 0; i<list1.length-l; i++)

{

Boolean flag = true;

for(int j = 0; j<list2.length; j++)

{

if(list1[i+j] != list2[j])

{

flag = false;

break;

}

}

if(flag) return true;

}

return false;

}

public static void main(String args[])

{

int[] l1 = {1,6,2,1,4,1,2,1,8};

int[] l2 = {1,2,2};

System.out.println(checkSubset(l1,l2));

}

}

In Java please:
Palindrome reads the same from left or right, mom for example. There is a palindrome which must be modified, if possible. Change exactly one character of the string to another character in the range ascii[a-z] so that the string meets the following three conditions:
a. The new string is lower alphabetically than the initial string.
b. The new string is the lowest value string alphabetically that can be created from the original palindrome after making only one change.
c. The new string is not a palindrome.
Return the new string, or, if it not possible to create a string meeting the criteria, return the string IMPOSSIBLE.
Example:
palindromeStr = 'aaabbaaa'
O Possible strings lower alphabetically than 'aaabbaaa' after one change are [aaaabaaa', 'aaabaaaa').
O aaaabaaa' is not a palindrome and is the lowest string that can be created from palindromeStr.

Answers

Answer:

See explaination

Explanation:

public class PalindromeChange {

public static void main(String[] args) {

System.out.println("mom to non palindrom word is: "+changTONonPalindrom("mom"));

System.out.println("mom to non palindrom word is: "+changTONonPalindrom("aaabbaaa"));

}

private static String changTONonPalindrom(String str)

{

int mid=str.length()/2;

boolean found=false;

char character=' ';

int i;

for(i=mid-1;i>=0;i--)

{

character = str.charAt(i);

if(character!='a')

{

found=true;

break;

}

}

if(!found)

{

for(i=mid+1;i<str.length();i++)

{

character = str.charAt(i);

if(character!='a')

{

found=true;

break;

}

}

}

// This gives the character 'a'

int ascii = (int) character;

ascii-=1;

str = str.substring(0, i) + (char)ascii+ str.substring(i + 1);

return str;

}

}

Write Scheme functions to do the following. You are only allowed to use the functions introduced in our lecture notes and the helper functions written by yourself. (a) Return all rotations of a given list. For example, (rotate ’(a b c d e)) should return ((a b c d e) (b c d e a) (c d e a b) (d e a b c) (e a b c d)) (in some order). (b) Return a list containing all elements of a given list that satisfy a given predicate. For example, (filter (lambda (x) (< x 5)) ’(3 9 5 8 2 4 7)) should return (3 2 4).

Answers

Answer:

Check the explanation

Explanation:

solution a:

def Rotate(string) :

n = len(string)

temp = string + string

for i in range(n) :

for j in range(n) :

print(temp[i + j], end = "")

print()

string = ("abcde")

Rotate(string)

solution b:

nums = [3,9,5,8,2,4,7]

res = list(filter(lambda n : n < 5, nums))

print(res)

Design and implement the Heap.h header using the given Heap class below:
template
class Heap
public:
Heap();
Heap(const T elements[], int arraySize); //
Remove the root from the heap and maintain the heap property
T remove() throw (runtime_error);
// Insert element into the heap and maintain the heap property
void add(const T& element);
// Get the number of element in the heap
int getSize() const;
private:
vector v;
Removing the root in a heap - after the root is removed, the tree must be rebuilt to maintain the heap property:
Move the last node to replace the root;
Let the root be the current node;
While (the current node has children and the current node is smaller than one of its children) Swap the current node with the larger of its children; The current node now is one level down;}
Adding a new node - to add a new node to the heap, first add it to the end of the heap and then rebuild the tree as follows:
Let the last node be the current node;
While (the current node is greater than its parent)
{Swap the current node with its parent; The current node now is one level up:}
To test the header file, write the heapSort function and use the following main program:
#include
#include "Heap.h"
using namespace std;
template
void heapSort(T list[], int arraySize) 1/
your code here .. p
int main()
const int SIZE = 9;
int list[] = { 1, 2, 3, 4, 9, 11, 3, 1, 2 }; heapSort(list, SIZE);
cout << "Sorted elements using heap: \n";
for (int i = 0; i < SIZE; i++) cout << list[i] << " ";
cout << endl;
system("pause");
return;
Sample output:
Sorted elements using heap:
1 1 2 3 3 4 7 9 11

Answers

Answer:

See explaination

Explanation:

/* Heap.h */

#ifndef HEAP_H

#define HEAP_H

#include<iostream>

using namespace std;

template<class T>

class Heap

{

public:

//constructor

Heap()

{

arr = nullptr;

size = maxsize = 0;

}

//parameterized constructor

Heap(const T elements[], int arraySize)

{

maxsize = arraySize;

size = 0;

arr = new T[maxsize];

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

{

add(elements[i]);

}

}

//Remove the root from the heap and maintain the heap property

T remove() //code is altered

{

T item = arr[0];

arr[0] = arr[size-1];

size--;

T x = arr[0];

int parent = 0;

while(1)

{

int child = 2*parent + 1;

if(child>=size) break;

if(child+1 < size &&arr[child+1]>arr[child])

child++;

if(x>=arr[child]) break;

arr[parent] = arr[child];

parent = child;

}

arr[parent] = x;

return item;

}

//Insert element into the heap and maintain the heap property

void add(const T&element)

{

if(size==0)

{

arr[size] = element;

size++;

return;

}

T x = element;

int child = size;

int parent = (child-1)/2;

while(child>0 && x>arr[parent])

{

arr[child] = arr[parent];

child = parent;

parent = (child-1)/2;

}

arr[child] = x;

size++;

}

//Get the number of element in the heap

int getSize() const

{

return size;

}

private:

T *arr; //code is altered

int size, maxsize;

};

#endif // HEAP_H

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* main.cpp */

#include<iostream>

#include "Heap.h"

using namespace std;

template <typename T>

void heapSort(T list[], int arraySize)

{

Heap<T> heap(list, arraySize);

int n = heap.getSize();

for(int i=n-1; i>0; i--)

{

list[i] = heap.remove();

}

}

int main()

{

const int SIZE = 9;

int list[] = {1, 7, 3, 4, 9, 11, 3, 1, 2};

heapSort<int>(list, SIZE);

cout << "Sorted elements using heap: \n";

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

cout << list[i] << " ";

cout <<endl;

system("pause");

return 0;

}

Write a program to read as many test scores as the user wants from the keyboard (assuming at most 50 scores). Print the scores in (1) original order, (2) sorted from high to low (3) the highest score, (4) the lowest score, and (5) the average of the scores. Implement the following functions using the given function prototypes: void displayArray(int array[], int size) - Displays the content of the array void selectionSort(int array[], int size) - sorts the array using the selection sort algorithm in descending order. Hint: refer to example 8-5 in the textbook. int findMax(int array[], int size) - finds and returns the highest element of the array int findMin(int array[], int size) - finds and returns the lowest element of the array double findAvg(int array[], int size) - finds and returns the average of the elements of the array

Answers

Answer: Provided in the explanation segment

Explanation:

Below is the code to carry out this program;

/* C++ program helps prompts user to enter the size of the array. To display the array elements, sorts the data from highest to lowest, print the lowest, highest and average value. */

//main.cpp

//include header files

#include<iostream>

#include<iomanip>

using namespace std;

//function prototypes

void displayArray(int arr[], int size);

void selectionSort(int arr[], int size);

int findMax(int arr[], int size);

int findMin(int arr[], int size);

double findAvg(int arr[], int size) ;

//main function

int main()

{

  const int max=50;

  int size;

  int data[max];

  cout<<"Enter # of scores :";

  //Read size

  cin>>size;

  /*Read user data values from user*/

  for(int index=0;index<size;index++)

  {

      cout<<"Score ["<<(index+1)<<"]: ";

      cin>>data[index];

  }

  cout<<"(1) original order"<<endl;

  displayArray(data,size);

  cout<<"(2) sorted from high to low"<<endl;

  selectionSort(data,size);

  displayArray(data,size);

  cout<<"(3) Highest score : ";

  cout<<findMax(data,size)<<endl;

  cout<<"(4) Lowest score : ";

  cout<<findMin(data,size)<<endl;

  cout<<"(5) Lowest scoreAverage score : ";

  cout<<findAvg(data,size)<<endl;

  //pause program on console output

  system("pause");

  return 0;

}

 

/*Function findAvg that takes array and size and returns the average of the array.*/

double findAvg(int arr[], int size)

{

  double total=0;

  for(int index=0;index<size;index++)

  {

      total=total+arr[index];

  }

  return total/size;

}

/*Function that sorts the array from high to low order*/

void selectionSort(int arr[], int size)

{

  int n = size;

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

  {

      int minIndex = i;

      for (int j = i+1; j < n; j++)

          if (arr[j] > arr[minIndex])

              minIndex = j;

      int temp = arr[minIndex];

      arr[minIndex] = arr[i];

      arr[i] = temp;

  }

}

/*Function that display the array values */

void displayArray(int arr[], int size)

{

  for(int index=0;index<size;index++)

  {

      cout<<setw(4)<<arr[index];

  }

  cout<<endl;

}

/*Function that finds the maximum array elements */

int findMax(int arr[], int size)

{

  int max=arr[0];

  for(int index=1;index<size;index++)

      if(arr[index]>max)

          max=arr[index];

  return max;

}

/*Function that finds the minimum array elements */

int findMin(int arr[], int size)

{

  int min=arr[0];

  for(int index=1;index<size;index++)

      if(arr[index]<min)

          min=arr[index];

  return min;

}

cheers i hope this help!!!

Suppose you are given a text file. Design a Python3 program to encrypt/decrypt that text file as follows:
If the character is an upper case character then shift that character forward, s characters forward in the alphabet.
If the character is a lower case character then shift that character backwards, s characters backwards in the alphabet.
If the character is a numeric character then shift that character also backwards, s characters backwards in the 1-digit numbers set {0,1,2,3,4,5,6,7,8,9}.
You must design two functions; one to encrypt. The other one is to decrypt. All white space and punctuation marks must be ignored(cannot be changed). If you reach Z, or A, the shifting may continue as a cycle(A comes after Z, Z comes before A). Both files (original text file and the encrypted text file) must be stored in the working directory of Python.
An example;
Let s=1 and the text file:
11300Hello World
Then encoded text file;
002991dkkn Xnqke

Answers

Answer:

Explanation:

Please find attachment for the Python program

Which term describes the order of arrangement of files and folders on a computer?
File is the order of arrangement of files and folders.

Answers

Answer:

Term describes the order of arrangement of files and folders on a computer would be ORGANIZATION.

:) Hope this helps!

Answer:

The term that describes the order of arrangement of files and folders on a computer is organization.

Explanation:

Which of the following is a component of slides

Answers

i need a picture to answer.

This represents a group of Book values as a list (named books). We can then dig through this list for useful information and calculations by calling the methods we're going to implement. class Library: Define the Library class. • def __init__(self): Library constructor. Create the only instance variable, a list named books, and initialize it to an empty list. This means that we can only create an empty Library and then add items to it later on.

Answers

Answer:

class Library:      def __init__(self):        self.books = [] lib1 = Library()lib1.books.append("Biology") lib1.books.append("Python Programming Cookbook")

Explanation:

The solution code is written in Python 3.

Firstly, we can create a Library class with one constructor (Line 2). This constructor won't take any input parameter value. There is only one instance variable, books, in the class (Line 3). This instance variable is an empty list.

To test our class, we can create an object lib1 (Line 5).  Next use that object to add the book item to the books list in the object (Line 6-8).  

Assume the existence of an UNSORTED ARRAY of n characters. You are to trace the CS111Sort algorithm (as described here) to reorder the elements of a given array. The CS111Sort algorithm is an algorithm that combines the SelectionSort and the InsertionSort following the steps below: 1. Implement the SelectionSort Algorithm on the entire array for as many iterations as it takes to sort the array only to the point of ordering the elements so that the last n/2 elements are sorted in increasing (ascending) order. 2. Implement the InsertionSort Algorithm to sort the first half of the resulting array elements so that these elements are sorted in decreasing (descending) order.

Answers

Answer:

class Main {

  public static void main(String[] args) {

      char arr[] = {'T','E','D','R','W','B','S','V','A'};

      int n = arr.length;

      System.out.println("Selection Sort:");

      System.out.println("Iteration\tArray\tComparisons");

      long comp1 = selectionSort(arr);

      System.out.println("Total comparisons: "+comp1);

      System.out.println("\nInsertion Sort:");

      System.out.println("Iteration\tArray\tComparisons");

      long comp2 = insertionSort(arr);

      System.out.println("Total Comparisons: "+comp2);

      System.out.println("\nOverall Total Comparisons: "+(comp1+comp2));

  }

  static long selectionSort(char arr[]) {

      // applies selection sort for n/2 elements

      // returns number of comparisons

      int n = arr.length;

      long comparisons = 0;

 

      // One by one move boundary of unsorted subarray

      for (int i = n-1; i>=n-n/2; i--) {

              // Find the minimum element in unsorted array

              int max_idx = i;

              for (int j = i-1; j>=0; j--) {

                      // there is a comparison everytime this loop returns

                      comparisons++;

                      if (arr[j] > arr[max_idx])

                              max_idx = j;

              }

              // Swap the found minimum element with the first

              // element

              char temp = arr[max_idx];

              arr[max_idx] = arr[i];

              arr[i] = temp;

              System.out.print(n-1-i+"\t");

              printArray(arr);

              System.out.println("\t"+comparisons);

      }

     

      return comparisons;

  }

  static long insertionSort(char arr[]) {

      // applies insertion sort for n/2 elements

      // returns number of comparisons

      int n = arr.length;

      n = n-n/2;   // sort only the first n/2 elements

      long comparisons = 0;

      for (int i = 1; i < n; ++i) {

          char key = arr[i];

          int j = i - 1;

          /* Move elements of arr[0..i-1], that are

                  greater than key, to one position ahead

                  of their current position */

          while (j >= 0) {

              // there is a comparison everytime this loop runs

              comparisons++;

              if (arr[j] > key) {

                  arr[j + 1] = arr[j];

              } else {

                  break;

              }

              j--;

          }

          arr[j + 1] = key;

          System.out.print(i-1+"\t");

          printArray(arr);

          System.out.println("\t"+comparisons);

      }

      return comparisons;

  }  

  static void printArray(char arr[]) {

      for (int i=0; i<arr.length; i++)

          System.out.print(arr[i]+" ");

  }

}

Explanation:

Explanation is in the answer.

D-H public key exchange Please calculate the key for both Alice and Bob.
Alice Public area Bob
Alice and Bob publicly agree to make
N = 50, P = 41
Alice chooses her Bob
picks his
Private # A = 19 private #
B= ?
------------------------------------------------------------------------------------------------------------------------------------------
I am on Alice site, I choose my private # A = 19.
You are on Bob site, you pick up the private B, B and N should have no common factor, except 1.
(Suggest to choose B as a prime #) Please calculate all the steps, and find the key made by Alice and Bob.
The ppt file of D-H cryptography is uploaded. You can follow the steps listed in the ppt file.
Show all steps.

Answers

Answer:

See explaination

Explanation:

Please kindly check attachment for the step by step solution of the given problem.

Rewrite this if/else if code segment into a switch statement int num = 0; int a = 10, b = 20, c = 20, d = 30, x = 40; if (num > 101 && num <= 105) { a += 1; } else if (num == 208) { b += 1; x = 8; } else if (num > 208 && num < 210) { c = c * 3; } else { d += 1004; }

Answers

Answer:

public class SwitchCase {

   public static void main(String[] args) {

       int num = 0;

       int a = 10, b = 20, c = 20, d = 30, x = 40;

       switch (num){

           case 102: a += 1;

           case 103: a += 1;

           case 104: a += 1;

           case 105: a += 1;

           break;

           case 208: b += 1; x = 8;

           break;

           case 209: c = c * 3;

           case 210: c = c * 3;

           break;

           default: d += 1004;

       }

   }

}

Explanation:

Given above is the equivalent code using Switch case in JavaThe switch case test multiple levels of conditions and can easily replace the uses of several if....elseif.....else statements.When using a switch, each condition is treated as a separate case followed by a full colon and the the statement to execute if the case is true.The default statement handles the final else when all the other coditions are false

Consider the following relations:
Emp(eid: integer, ename: varchar, sal: integer, age: integer, did: integer) Dept(did: integer, budget: integer, floor: integer, mgr_eid: integer) Salaries range from $10,000 to $100,000, ages vary from 20 to 80, each department has about five employees on average, there are 10 floors, and budgets vary from $10,000 to $1 million. You can assume uniform distributions of values. For each of the following queries, which of the listed index choices would you choose to speed up the query.
1. Query: Print ename, age, and sal for all employees.
A) Clustered hash index on fields of Emp.
B) Unclustered hash index on fields of Emp.
C) Clustered B+ tree index on fields of Emp.
D) Unclustered hash index on fields of Emp.
E) No index.
2. Query: Find the dids of departments that are on the 10th floor and have a budget of less than $15,000.
A) Clustered hash index on the floor field of Dept.
B) Unclustered hash index on the floor field of Dept.
C) Clustered B+ tree index on fields of Dept.
D) Clustered B+ tree index on the budget field of Dept.
E) No index.

Answers

Answer:

Check the explanation

Explanation:

--Query 1)

SELECT ename, sal, age

FROM Emp;

--Query 2)

SELECT did

FROM Dept

WHERE floot = 10 AND budget<15000;

A user has called the company help desk to inform them that their Wi-Fi enabled mobile device has been stolen. A support ticket has been escalated to the appropriate team based on the corporate security policy. The security administrator has decided to pursue a device wipe based on corporate security policy. However, they are unable to wipe the device using the installed MDM solution. What is one reason that may cause this to happen?

Answers

Answer:

The software can't locate the device

Explanation:

The device wasn't properly setup in order for the software to locate it.

5.14 ◆ Write a version of the inner product procedure described in Problem 5.13 that uses 6 × 1 loop unrolling. For x86-64, our measurements of the unrolled version give a CPE of 1.07 for integer data but still 3.01 for both floating-point data. A. Explain why any (scalar) version of an inner product procedure running on an Intel Core i7 Haswell processor cannot achieve a CPE less than 1.00. B. Explain why the performance for floating-point data did not improve with loop unrolling.

Answers

Answer:

(a) the number of times the value is performs is up to four cycles. and as such the integer i is executed up to 5 times.  (b)The point version of the floating point can have CPE of 3.00, even when the multiplication operation required is either 4 or 5 clock.

Explanation:

Solution

The two floating point versions can have CPEs of 3.00, even though the multiplication operation demands either 4 or 5 clock cycles by the latency suggests the total number of clock cycles needed to work the actual operation, while issues time to specify the minimum number of cycles between operations.

Now,

sum = sum + udata[i] * vdata[i]

in this case, the value of i performs from 0 to 3.

Thus,

The value of sum is denoted as,

sum = ((((sum + udata[0] * vdata[0])+(udata[1] * vdata[1]))+( udata[2] * vdata[2]))+(udata[3] * vdata[3]))

Thus,

(A)The number of times the value is executed is up to 4 cycle. And the integer i performed up to 5 times.

Thus,

(B) The floating point version can have CPE of 3.00, even though the multiplication operation required either 4 or 5 clock.

What is the fastest typing speed ever recorded? Please be specific!

Answers

Answer:

250 wpm for almost an hour straight. This was recorded by Barbara Blackburn in 1946.

after turning the volume all the way up on the speakers you still can't hear any sound which of the following should be your the next step

Answers

Answer:

check if its pluged in

Explanation:

Other Questions
Each of Mrs. Moore's students uses a certain number of pencils per weekof school. There are 22 students in Mrs. Moore's class. If there are 36weeks of school and Mrs. Moore's students use 3168 pencils in a schoolyear, how many pencils does each student use per week? PLZ HELP! WILL MARK BRAINLIESTTell what whole number you can substitute for x in the following list so the numbers are ordered from least to greatest.1/x , x/8, 65%x= find the missing angle in the triangle What is a ring? On the North and South: who killed Reconstruction Find the lowest common denominator for the fractions shown.8/51 19/85a. 255b. 17c. 4,335 How did African American participation in North Carolina government change during Constitutional Reconstruction? help plsssssssssssssssssssssss again The value of a car decreases as shown in the table below.A 2-column table with 6 rows. The first column is labeled years after purchase with entries 0, 1, 2, 3, 4, 5. The second column is labeled value (dollar sign) with entries 25,000; 18,000; 14,000; 10,500; 8,000; 6,000.Which statements are true? Check all that apply. in edgeThe function that best represents the data is f(x) = 24,512(0.755)x.The function that best represents the data is f(x) = 554x2 5,439x + 24,600.The function decreases indefinitely.It is reasonable to interpolate to the value of the car at 4.5 years. It is reasonable to extrapolate to 40 years. Need the answer ASAP There are 21 cards numbered 1 to 21.if you pick a card what is the probability that choose an odd number or a two?1/24/711/2144/147 Work in pairs. Complete the sentences about the future of Internet communication.1. How is the Internet__________ (change) in the future?2. We ____________(not have to) search the Internet for what we want.3. It (know) what we want before we do.4. All companies are ___________(study) what people do on the Internet even more than they do now.5. The companies ___________(tell) us what they think we need Which polynomials are in standard form? KSB is considering a project that will require $39,000 in net working capital and $68,000 in fixed assets. The project is expected to produce annual sales of $78,500 with associated cash costs of $41,000. The project has a four-year life. The company uses straight-line depreciation to a zero book value over the life of the project. Ignore bonus depreciation. The tax rate is 25 percent. What is the operating cash flow for this project The conversion rate is restated for all stock dividends and splits. Coffee had the following stock transactions in 2005 and 2006: 1/1/2005 - Sold 30,000 shares of common stock at $20 per share. 1/1/2005 - Sold 10,000 shares of preferred stock at $100 per share. 4/1/2005 - Issued at 50 percent stock dividend when the market price is $26 per share. 9/1/2005 - Purchased 4,000 treasury shares at $30 per share. 10/1/2005 - Sold 1,000 of the treasury shares at $32 per share. 11/1/2005 - Sold 2,000 of the treasury shares at $25 per share. 12/1/2005 - Issued a 2-1 for stock split. 12/20/2005 - Declared the required dividend to preferred stock holders and a $.25 per share dividend to common stockholders. Dividends are payable on 12/31/2005.Prepare journal entries to record all of the above business events A family has three children. The oldest child is 4 years older than themiddle child, and the youngest child is 2 years younger than themiddle child. The sum of the ages of the children is 26.RHow many years old is the youngest child?years oldQ The diagram above shows the countries places on a spectrum based on their __________.A.economic systemsB.economic productionC.imports and exportsD.industrialization Which expression shows a way to find 25% of 1000? A new type of fish has been discovered. It has vibration receptors on its snout and virtually nonexistent eyes. Based on these characteristics, in which part of the ocean is this fish most likely found? The following costs result from the production and sale of 5,000 drum sets manufactured by Tight Drums Company for the year ended December 31, 2017. The drum sets sell for $350 each. The company has a 25% income tax rate. Variable production costs Plastic for casing $ 185,000 Wages of assembly workers 510,000 Drum stands 230,000 Variable selling costs Sales commissions 175,000 Fixed manufacturing costs Taxes on factory 5,000Factory maintenance 10,000 Factory machinery depreciation 70,000 Fixed selling and administrative costs Lease of equipment for sales staff 10,000 Accounting staff salaries 60,000 Administrative management salaries 140,000Prepare contribution margin income statement for the company. How was life for civilians different in World War II as compared with past wars?