Java-
Create a new class named Forest that has a 2D array of integers to store a forest.
Create a private inner class Position to store the row and column of the current cell.
Create a Depth First Search Method that uses a stack to remove the current tree and search its neighbors based on the following pseudocode:
// given a forest "f" // store positions on fire Stack<Position> cellsToExplore // the forest is aflame! for each tree in the top row: add position to cellsToExplore mark tree as "on fire" // continue lighting neighbors on fire while cellsToExplore is not empty pop the stack into currentPosition return true if currentPosition is on the bottom row for each neighboring tree push location onto the stack mark tree as "on fire" // must not have reached the bottom row... return false
In: Computer Science
In this problem, we provide you with a Java file called Question2.java. Suppose that there is an array and let us call this array, items. The array items contains n integers. These n integers are in a completely random order in the array. What you are asked to do is to reorder the items in the array such that all the negative integers come before all the zeros and all the positive integers appear at the end. Note, this question is not asking you to sort the numbers in the array. It is asking you to reorder them
In this first example, you can see that the array initially contains the integers 7, −3, 0, 0, 8 and −2. Now, this is in some random order. What you must do to this array, is to reorder the numbers such that the array has three distinct pieces (also called constraints) represented by < 0, == 0 and > 0. You can see that in the first region, we place all the numbers that are less than 0, followed by all zeros and then followed by any numbers that are greater than 0. The numbers within each region can be in any order, as long as they happen to fulfill the constraint.
2. You can only visit all the numbers in the array once. i.e., you are not allowed to have nested loops. Neither can you create a new array or use an array list. You should be able to work on this problem simply by visiting every number once. You must mutate the array that is already provided to you and make changes to this array itself.
3. Do not sort any numbers. If you were to sort the numbers, you would receive zero for this question.
4. The numbers within each region can be in any order, as long as they happen to fulfill the constraint.
5. You cannot assume that there will be at least a single zero in the array. You may very well have an array with all zeros or an array that contains no zero. Assuming that the array contains only negative numbers and positive numbers (≥ 1) If this is the case, you will proceed with reordering the items in the array such that you have negative numbers followed by positive numbers. 6. We provide to you the following methods that must be completed
starter code:
package 3; //Make sure to copy/paste the honor code and fill in all the required details. //If you do not complete the honor code, your assignment will not get marked. import java.util.Arrays; public class Question2 { /* * TODO: You are asked to complete the method * rearranging. This method takes in as input an * array of ints and returns back nothing (void). * You cannot change the function * signature of this method. Your method question2 must call * the swap method. Scroll down to find the swap method. * You cannot use any kind of sorting to answer this question. */ public static void question2(int[] items) { } /* * TODO: You are asked to complete the method * swap. This method takes in as input two ints * and an array of ints. The int i and int j * are the index i and index j in the array items. * You are asked to swap the value at the index i in items * with the value at the index j. You cannot change the function * signature of this method. This method must be called inside question2. */ private static void swap(int i,int j,int[] items) { } /* * Do not write any code inside the main method and expect it to get marked. * Any code that you write inside the main method will be ignored. However, * you are free to edit the main function in any way you like for * your own testing purposes. */ public static void main(String[] args) { int [] items={-7,-3,20,10,8,2}; Question2.question2(items); System.out.println(Arrays.toString(items)); //must print [-7, -3, 10, 8, 2, 20] int [] items1={1,1,1,1,1,1,1,1}; Question2.question2(items1); System.out.println(Arrays.toString(items1)); //must print [1, 1, 1, 1, 1, 1, 1, 1] int [] items2={1,2,3,4,5,6,7,8,9}; Question2.question2(items2); System.out.println(Arrays.toString(items2)); //must print [2, 3, 4, 5, 6, 7, 8, 9, 1] int [] items3={6,7,8,0,1,2,3,-1,-2}; Question2.question2(items3); System.out.println(Arrays.toString(items3)); //must print [-2, -1, 0, 1, 2, 3, 8, 7, 6] int [] items4={0,0,0,0,1,2,3,-1,-2,-3}; Question2.question2(items4); System.out.println(Arrays.toString(items4)); //must print [-3, -2, -1, 0, 0, 0, 0, 3, 2, 1] int [] items5={-1,4,5,6,0,0,0,-2}; Question2.question2(items5); System.out.println(Arrays.toString(items5)); //must print [-1, -2, 0, 0, 0, 6, 5, 4] } }
In: Computer Science
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
#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;
}
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 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 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 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 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
In: Computer Science
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' 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 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 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 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) 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