Questions
Programming language is Java. Consider you have already created a validateString(String str) method that validates a...

Programming language is Java.

Consider you have already created a validateString(String str) method that validates a String to ensure it contains exactly 4 characters.

Create code that calls this method, sending user input as an argument (actual parameter). The user should be continuously prompted to enter a different string and informed of an error if the method returns false.

In: Computer Science

Run the following code and explain what the code does Run this code at least twice...

  1. Run the following code and explain what the code does

  • Run this code at least twice and take screenshots
  • Explain what the code does
  • What is the running result supposed to be
  • What caused this issue?

#include <thread>

#include <iostream>

using namespace std;

const unsigned int NTHREADS = 20;

const int ITERS = 10000000;

int counter;

void increment()

{

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

                     counter++;

             

}

void decrement()

{

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

                     counter--;

             

}

int main()

{

       cout << "The counter is " << counter << endl;

      

              thread *threads = new thread[NTHREADS];

      

              for (unsigned int i = 0; i<NTHREADS; i++)

              if (i % 2 == 0)

              threads[i] = thread(increment);

       else

              threads[i] = thread(decrement);

      

              for (unsigned int i = 0; i<NTHREADS; i++)

              threads[i].join();

      

              cout << "The counter is " << counter << endl;

      

              return 0;

}

  1. Mutex

A mutex (mutual exlusion) allows us to encapsulate blocks of code that should only be executed in one thread at a time.

Apply mutex to solve the issue in the previous code. Show your revised code and running result.

In: Computer Science

(a) When the two dice are rolled, find the value of X for the 36 possible...

(a) When the two dice are rolled, find the value of X for the 36 possible outcomes (i, j), where i and j are the numbers that appear on the first die and the second die, respectively. Assuming the random variable X is the sum of numbers that appear when a pair of dice is rolled.                                                                                                                                                                         

In: Computer Science

how do i program this to Java: Company X offers a 401k (Links to an external...

how do i program this to Java:

Company X offers a 401k (Links to an external site.) retirement plan that allows you to save a percentage of your salary every year.

Your investment will grow using a flat interest rate that you will provide as input.

The goal is to compute how much money you will have for retirement after a specified number of years.

This is just a basic calculation. No loops yet!

Input

Read the following from input. Make sure you prompt for input.

Salary - your salary will remain the same for all of your years of employment. Read in as int.

Percentage of Salary you will save for retirement each year. Read in as double so 6% = .06.

Interest Rate - the rate at which your retirement plan grows over the duration. Read in as double so 5% interest rate = .05.

Employment Years - the number of years you will work at Company X. Read in as int.

For the interest formula, just use the below:

Total Savings = Years of Employment * Percentage of Salary you save * Salary * (1 + Interest Rate)

Output

Your input variables as well as the amount you will have saved in retirement.

Please prompt the user. Include a line that says please enter in your salary percentage saved interest rate and employment years separated by a space.

Sample Run

Enter input: salary savings_rate interest_rate years_employed
> 70000 .10 .06 30
Salary: 70000
Savings rate:0.1
Interest rate:0.06
Years of Employment: 30
Retirement Savings: 222600.0

In: Computer Science

Circle Object Python program Compute the area and perimeter of a circle using Python classes. take...

Circle Object Python program

Compute the area and perimeter of a circle using Python classes. take the radius from the user and find the area and perimeter of a circle

please use comments to explain so i better understand

In: Computer Science

Need to write a c program Program prints a message telling the user to push a...

Need to write a c program

  • Program prints a message telling the user to push a key to start the game.

  • Once in game, output tells the player which key to push. The key to press should be determined randomly.

    • Game runs continuously until the user reaches a loose condition.

      • A wrong key is pressed

In: Computer Science

Create a Python function called eulersFormula that returns the value of Euler's formula e^(iπ) + 1

Create a Python function called eulersFormula that returns the value of Euler's formula
e^(iπ) + 1

In: Computer Science

Write a method public static <E> List<List<E>> filterMinLength(List<List<E>> listOfLists, int minLength) that given a list of...

Write a method public static <E> List<List<E>> filterMinLength(List<List<E>> listOfLists, int minLength) that given a list of lists and a minimum length returns a new list of lists, containing only the lists that are at least as long as the minimum length in the same order they appeared in the input. The original list must not be modified.

For example, if listOfLists = [[1, 2, 3], [], [4, 5], [6, 7, 8, 9]] and minLength = 3, then the method should return a new list containing two lists: [[1, 2, 3], [6, 7, 8, 9]].

For full credit, your method must correctly use generics, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness.

You may assume List and ArrayList are correctly imported. You may not import other classes.

In: Computer Science

Please code the program showing the output below. using C language 1. Using 'if' or 'while'...

Please code the program showing the output below. using C language

1. Using 'if' or 'while' or 'for' and 'break' statement / only using <stdio.h>

A

bC

dEf

GhIj

KlMnO

2. a program that identifies the largest number that can be expressed in short.

Using only loop (ex.for,if,while) and break statement

only using <stdio.h>

In: Computer Science

Suppose that you are given a set of words; and two words from the set: word...

Suppose that you are given a set of words; and two words from the set: word 1 and word 2.

Write a program which will transform word 1 into word 2 by changing a single letter in word 1 at a time.

Every transition that word 1 takes will have to be in the set of words.

You must output the smallest sequence of transitions possible to convert word 1 into word 2.

You may assume that all the words in the dictionary are the same length.

The first line will be word 1 and word 2 separated by a comma, followed by the set of words. The set of words will be terminated by a ‘-1’.

Input:

DOG,GOD

DOG

BOG

GOG

ABH

GOD

THU

IOP

-1

Output:

DOG -> GOG -> GOD

I have a code that does this but its all done in a textfile, I need it to be all on the console(using cin,cout and not the fstream)

#include
#include
#include
#include
#include
#include
#include

using namespace std;

class WordLadder {

private:
list dict; //list of possible words in ladder
void printstack(stack stack, ofstream &outfile);
bool wordcompare(string word, string dictword);

public:
WordLadder(const string &file);
void outputLadder(const string &start, const string &end, const string &outputFile);
};
WordLadder::WordLadder(const string &file) {
string word;
ifstream infile;
infile.open(file.c_str());
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile,word);
if (word.size() != 5) {
cout << "Warning: Word longer than 5 characters detected in dictionary." << endl;
}
dict.push_back(word.c_str());
}
infile.close();
return;
} else {
cout << "Error opening input file." << endl;
return;
}
}
void WordLadder::outputLadder(const string &start, const string &end, const string &outputFile) {

cout << "Finding word ladder from " << start << " to " << end << ": ";
ofstream outfile;
outfile.open(outputFile.c_str());
if (!outfile.is_open()) {
cout << "Opening output file failed." << endl;
return;
}
// set up the stuff
queue< stack > queue;
stack< string > stack;
string word;
list::iterator it;
bool startgood = false, endgood = false;

// initial validity tests
for (it=dict.begin();it!=dict.end();++it) {
if (*it == start) {
startgood = true;
}
if (*it == end) {
endgood = true;
}
}
if (!startgood || !endgood) {
cout << "Starting or ending word was not found in the dictionary." << endl;
return;
}
if (start == end) {
outfile << start;
return;
}
stack.push(start);
queue.push(stack);

// find the first word, delete it
dict.remove(start);
while(!queue.empty()) {
// get the word off of the top of the front stack
word = queue.front().top();
for (it=dict.begin();it!=dict.end();++it) {
// wordcompare will decide if the word is off by one from the dictionary word.
if (wordcompare(word,*it)) {
if (*it == end) {
// if the off by one word is the last word
// the ladder contains the entire stack -- output and return.
queue.front().push(end);
//print the stack
printstack(queue.front(),outfile);
//cout << "Operations: " << opers << endl << endl;
return;
}
// otherwise, create a copy of the front stack and push the
// off by one word from dictionary
stack = queue.front();
stack.push(*it);
queue.push(stack);
it = dict.erase(it);
// decrement iterator by one to correct for the advanced iterator
// returned by the std::list::erase function
it--;
}
}
queue.pop();
}
// if a word ladder is not found, then do this
if (outfile.is_open()) {
outfile << "No Word Ladder Found!!";
cout << "No Word Ladder Found!!";
}
}


bool WordLadder::wordcompare(string word, string dictword) {
int hits = 0;
for (int i=0; i<5; i++) {
if (word[i] == dictword[i]) { hits++; }
}
if (hits == 4) {
return true;
} else {
return false;
}
}

void WordLadder::printstack(stack stack, ofstream &outfile) {

int i = 0;
vector ladder;
while (!stack.empty()) {
ladder.push_back(stack.top());
stack.pop();
i++;
}

if (outfile.is_open()) {
while (i!=0) {
i--;
outfile << ladder.at(i);
cout << ladder.at(i);
if (i!=0) {
outfile << " ";
cout << " ";
}
}
cout << endl;
}
}

int main() {
string dictFile, wordBegin, wordEnd, outFile;
cout << "Enter the name of the dictionary file: ";
cin >> dictFile;
cout << endl;
cout << "Enter the name of the output file: ";
cin >> outFile;
cout << endl;
cout << "Enter the first word: ";
cin >> wordBegin;
cout << endl;
while (wordBegin.size() != 5) {
cout << "Word must have exactly 5 characters." << endl
<< "Please reenter the first word: ";
cin >> wordBegin;
cout << endl;
}
cout << "Enter the last word: ";
cin >> wordEnd;
cout << endl;
while (wordEnd.size() != 5) {
cout << "Word must have exactly 5 characters." << endl
<< "Please reenter the last word: ";
cin >> wordEnd;
cout << endl;
}
WordLadder wl(dictFile);
wl.outputLadder(wordBegin, wordEnd, outFile);
return 0;
}

In: Computer Science

In a game of Tic Tac Toe, two players take turns making an available cell in...

In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win.

Write a program in Java that emulates a Tic Tac Toe game.

When you are done, a typical session will look like this:

 Welcome to tic-tac-toe.
 Enter coordinates for your move following the X and O prompts.
   1 2 3
A   | | 
   -----
B   | | 
   -----
C   | |

X:A2
   1 2 3
A   |X| 
   -----
B   | | 
   -----
C   | |

O:B3
   1 2 3
A   |X| 
   -----
B   | |O
   -----
C   | |

And so on. Illegal moves will prompt the user again for a new move. A win or a stalemate will be announced, mentioning the winning side if any. The program will terminate whenever a single game is complete.

This file has the general framework of the TicTacToe class. An object of this class will represent a tic-tac-toe "board". The board will be represented internally by a two dimensional array of characters (3 x 3), and by a character indicating who's turn it is ('X' or 'O'). These are stored in the class instance variables as follows.

private char[][] board;
private char player; // 'X' or 'O'

You will need to define the following methods:

1. A constructor:

public TicTacToe()

to create an empty board, with initial value of a space (' ')

2. play method

public play(String position)

if position represents a valid move (e.g., A1, B3), add the current player's symbol to the board and return true. Otherwise, return false.

3. switchTurn method

public void switchTurn()

switches the current player from X to O, or vice versa.

4. won method

public boolean won()

Returns true if the current player has filled three in a row, column or either diagonal. Otherwise, return false.

5. stalemate method

public boolean stalemate()

Returns true if there are no places left to move;

6. printBoard method

 public void printBoard()

prints the current board

7. Use the following test code in your main method to create a TicTacToe object and print it using the printBoard method given, so as to test your code. Your printBoard method should produce the first board in the example above.

public static void main(String[] args) {

       Scanner in = new Scanner(System.in);
       TicTacToe game = new TicTacToe();
       System.out.println("Welcome to Tic-tac-toe");
       System.out.println("Enter coordinates for your move following the X and O prompts");
       
       while(!game.stalemate()) 
       {
              game.printBoard();
              System.out.print(game.getPlayer() + ":");

              //Loop while the method play does not return true when given their move.
              //Body of loop should ask for a different move
              while(!game.play(in.next()))
              {
                    System.out.println("Illegal move. Enter your move.");
                    System.out.print(game.getPlayer() + ":");
               }
              //If the game is won, call break;
              if(game.won())
                  break;

              game.printBoard();
              //Switch the turn
              game.switchTurn();

        }
        game.printBoard();
        if(game.won())
        {
             System.out.println("Player "+game.getPlayer()+" Wins!!!!");
        } 
        else 
        {
             System.out.println("Stalemate");
        }
}

In: Computer Science

This is all that was given. Write a program in a PL of your choice to...

This is all that was given.

Write a program in a PL of your choice to create the followings Output:

A table(7 rows), you see below, showing 35 names grouped in 7 lines.
The first column is the chosen Programming Language to develop and present by the group.

PLs All group Names

C n26 n06 n28 n16 n30
C++ n31 n07 n33 n17 n35
C# n03 n08 n13 n18 n23
Python n04 n09 n14 n19 n24
java n05 n10 n15 n20 n25
JS n01 n27 n11 n29 n21
Ruby n02 n32 n12 n34 n22
Do you need more ? <0,1>1

PLs All group Names

C n01 n31 n11 n04 n21
C++ n02 n07 n12 n09 n22
C# n28 n33 n13 n14 n15
Python n16 n17 n18 n19 n20
java n30 n35 n23 n24 n25
JS n26 n27 n03 n29 n05
Ruby n06 n32 n08 n34 n10
Do you need more ? <0,1>0

- Names are unique, they should not be duplicated as this (nam7, name7), they can be real student names.

- The program should allow the user to rearrange the students and the groups at will.
Example: select many students in one of several groups :  

if(( student_numbers %7) ==0 ) set student in group 1 (first group), and

if ((student_numbers %7) ==1 ) in group 2 (second group)

if ((student_numbers %7) ==2 ) in group 3 (third group)

if ((student_numbers %7) ==3 ) in group 4 (fourth group)

if (((student_numbers %7) ==4) in group 5 (fifth group)

if ((student_numbers %7 )==5) in group 6 (sixth group)

if ((student_numbers %7) ==6) in group 7 (seventh group)


Note: here % modulo function was used, but we can use other methods of classification (formula, or function like).

Assignment: (Write a program in any PL and submit. (Required for grading))

------------------------------------------------------------------

Here is a pdf (repeated copy):

-------------------------------------

Write a program in a PL of your choice to create the followings Output:
A table (7 rows), you see below, showing 35 names grouped in 7 lines.
The first column is the chosen Programming Language to develop and present by the group.

- Names are unique, they should not be duplicated as this (nam7, name7), they can be real
student names.
- The program should allow the user to rearrange the students and the groups at will.
Example: select many students in one of several groups:
If (( student_numbers %7) ==0) set student in group 1 (first group), and
if ((student_numbers %7) ==1) in group 2 (second group)
if ((student_numbers %7) ==2) in group 3 (third group)
if ((student_numbers %7) ==3) in group 4 (fourth group)
if (((student_numbers %7) ==4) in group 5 (fifth group)
if ((student_numbers %7) ==5) in group 6 (sixth group)
if ((student_numbers %7) ==6) in group 7 (seventh group)
Note: here % modulo function was used, but we can use other methods of classification
(formula, or function like).

Assignment: (Write a program in any PL and submit. (Required for grading))
Input: list of PLs, and list of student names (generate these at random)
Output: the given Table (format) you see above

In: Computer Science

Write a C program that allows users to enter three runners name (up to 20 characters)...

Write a C program that allows users to enter three runners name (up to 20 characters) and their runtime (2 decimals)

(1) First and Last name

(2) Running time for 100 m ex. 9.96 seconds

your program should rank them in ascending order of their runtime. example:

usian Bolt - 9.96 sec - First Place

John doe - 9.99 sec - second Place

Pete Urel -10.11 sec - third place

BUT they fan tie for first place and no second place awarded

usian Bolt - 9.96 sec - First Place

John doe - 9.96 sec -First Place

Pete Urel -10.11 sec - third place

OR they can tie for second place and no third place awarded

usian Bolt - 9.96 sec - First Place

John doe - 10.11sec - second Place

Pete Urel -10.11 sec - second place

YOU CANNOT USE AN ARRAY DATA STRUCTURE TO STORE DATA FOR EACH RUNNER

In: Computer Science

Create a new Python 3 Jupyter Notebook. Create one python code cell for the problem below....

Create a new Python 3 Jupyter Notebook.

Create one python code cell for the problem below. Use any additional variables and comments as needed to program a solution to the corresponding problem. All functions should be defined at the top of the code in alphabetical order.

When done, download the ipynb file and submit it to the appropriate dropbox in the course's canvas page.

Problem:

  1. Define a function with the following characteristics:
    • The function's purpose will be calculating a factORRial (similar to a mathematical factorial but purposefully different in important ways), so it should be named appropriately.
    • It must accept one parameter, which is the number it will be calculating the factorrial of. Name this parameter appropriately.
    • It must have an appropriate docstring.
    • If the parameter is equal to1, define a new variable as 1. This new variable will be used as the return value, so name it accordingly
    • If the parameter is equal to or less than 0, define the same variable you created in the previous bullet point as 0. Use an "else-if" block for this logic.
    • In an "else" block:
      • Print out the value of the parameter in a nicely formatted message conveying that you are calculating the factorrial of that number.
      • Define a new variable to be the parameter minus 1.
      • Define another new variable as the factorrial of variable you just created in the previous bullet point. Use a recursive call to the function you are currently building to calculate that factorrial.
      • Multiply the parameter by the variable you just defined in the previous bullet point and store it in the variable you created earlier to hold the return value.
    • The last line of the function should return the variable you defined as the return value.
  2. In your main code section, call the function defined in step 1 to calculate the factorrial of 10 and store it in a variable.
  3. Next, call the same function to calculate the factorrial of -10 and store it in a different variable.
  4. Print out both of the results using a single format string with a friendly (or funny) message

Rubric:

  • Adequate comments, readability, etc.
  • Checks for case 1
  • Checks for case equal to or less than 0
  • Checks for everything else
  • Makes appropriate recursive call
  • Calculates factorrial of 10
  • Calculates factorrial of -10
  • Uses a format string for both calculations
  • Uses docstring
  • Prints parameter for each call of function in else block

In: Computer Science

Python program that simulates the rolling a die until the number 5 is first obtained. Repeat...

Python program that simulates the rolling a die until the number 5 is first obtained. Repeat the experiment 10,000 times and print out the “Average Number of Rolls to Obtain a Six on a Die”, along with the average value. Include the average number of rolls your program calculates as a comment

Please use comments to better explain what is happening

In: Computer Science