I am solving a problem called Car Fueling on coursera and I followed the pseudocode that had been given. The problem states:
You are going to travel to another city that is located d miles away from your home city. Your car can travel at most m miles on a full tank and you start with a full tank.
Along your way, there are gas stations at distances stop 1, stop 2, . . . , stop n from your home city. What is the minimum number of refills needed?
Input Format.
The first line contains an integer d.
The second line contains an integer m.
The third line specifies an integer n.
Finally, the last line contains integers stop 1, stop 2, . . . , stop n.
Output Format.
Assuming that the distance between the cities is d miles, a car can travel at most m miles on a full tank, and there are gas stations at distances stop 1, stop 2, . . . , stop n along the way, output the minimum number of refills needed. Assume that the car starts with a full tank. If it is not possible to reach the destination, output −1.
Here is the function to solve the problem:
int compute_min_refills(int dist, int tank, vector<int> & stops) {
int curref=0;//current position of the car
int numref=0;//number of refills
int lastref=0;//last position of the car
int n=stops.size();//the amount of stops to refill at
while(curref<=n){
if(curref>=n){return -1;}
lastref=curref;
while((curref<=n) && (stops[curref+1]-stops[lastref]<=tank)){curref=curref+1;}
if(curref==lastref){return -1;}
if(curref<=n){numref=numref+1;}
}
return numref;
}
When I submit, it fails on the first test case, but I don't know what could be causing it to give error.
The test case:
Input:
500
200
4
100 200 300 400
Your output:
1
Correct output:
2
I am trying to make characters with an output as such in Fortran but I don't know how to. I made one with columns of asterisks but now I need it to change to the image linked.
I am a novice at Fortran.
Here's my code for the columns:
program chardesign
integer complete
do complete = 1, 5
write (*, 10, advance='no')
10 format (' * ')
enddo
!Newline to complete
write (*, 10)
stop
end program chardesign
How can I go about this?
Since we can no longer restrain ourselves from offering solutions...
Suppose we had a file called diamond.txt that had the picture already drawn:
*
***
*****
*******
*********
*******
*****
***
*
I know it's not visible here, but each line in diamond.txt has sufficient trailing spaces to make it 9 characters long. Now we just need a program that copies diamond.txt to its output:
program diamond
implicit none
character(9) line
open(10,file='diamond.txt',status='old')
do
read(10,'(a)',end=20) line
write(*,'(a)') line
end do
20 continue
end program diamond
The program has a couple of new features: first off it has implicit none which forces the programmer to declare all variables, thus avoiding a common source of hard-to-trace programming errors. Then it declares a character variable character(9) line which creates a variable which always contains 9 characters. There are rules that govern what happens if you try to assign it to a string of lesser or greater length, but we won't do that here.
Then it opens the file diamond.txt. The unit number, 10, will be used to reference the file in subsequent I/O statements. The status='old' part will cause the program to abort if it can't find diamond.txt.
Then we have a do statement which means do forever. Of course we don't really want to 'do forever', so there should be some way to exit the loop from its body.
Now we have a read statement that reads from unit 10, which, due to our previous open statement, is our file diamond.txt. The end=20 part means that when the read statement tries to read past end-of-file execution jumps to statement number 20, which gets us out of the loop. The format (a) does character I/O. It is the same as (a9) because the program knows that the length of the character variable to be read, line, is 9, so it will try to read the next 9 characters from diamond.txt and put them in variable line. After the read statement is complete, the file pointer advances to the next line of diamond.txt.
Then the write statement just writes variable line to standard output, thus copying the current line of diamond.txt to the screen.
When it's done, the end=20 branch is taken getting us to the 20 continue statement after which the end line is encountered and execution terminates.
So how could we do this without an external file? We could just convert the picture into a format statement and then print according to the format:
1 format(' * '/ &
' *** '/ &
' ***** '/ &
' ******* '/ &
'*********'/ &
' ******* '/ &
' ***** '/ &
' *** '/ &
' * ')
print 1
end
So we have encountered a new format specifier, /, the 'slash', which advances I/O to the next record (or line). Also the free-format continuation character &, the 'ampersand', which means that the current line continues to the next noncomment line. Also the print statement where here print 1 has the same effect as write(*,1).
OK, but what if we wanted to carry out some kind of calculation to produce the picture? If we considered the picture to lie on a raster array where row i ran from 1 at the top to 9 at the bottom and column j ran from column 1 at the left to column 9 at the right, we might observe that the image is symmetric about i=5 and about j=5. If we considered i and j to run from -4 to 4 instead we might be able to see some patterns that enable us to take advantage of the symmetry now about the y-axis and x-axis. Accordingly we write a program that will print out the coordinates...
print"(9(1x:'(',i2,',',i2,')'))",[((i,j,j=-4,4),i=-4,4)];end
Now we have a couple of new program elements: there is an array constructor [stuff] which will create an array of the elements listed within the square brackets.
[(more_stuff,i=-4,4)] is an ac-implied-do which effectively creates a list by evaluating more_stuff sequentially for each value of i from -4 to 4, thus a list of 9 things.
[((still_more_stuff,j=-4,4),i=-4,4)] is a nested ac-impied-do which for each value of i makes a list by evaluating still_more_stuff sequentially for each value of j from -4 to 4, thus there is a list of 9*9=81 things.
Since still_more_stuff is i,j, i.e. 2 things, the array constructor creates an array of 162 things, each (i,j) pair with j varying faster than I.
The print statement has a format string surrounded by " double quotes rather than ' apostrophes so that we can use apostrophe-delimited strings in the format.
The 9(stuff) part is a repeat count that means to do the formats specified in stuff 9 times over.
The 1x format says just skip one space and the following colon just separates it from the next format item. We can use , (comma), : (colon), or / (slash) to separate format items. As the reader will recall, slash skips to the next record; for the purposes or the current discussion let's ignore the distinction between comma and colon.
The i2 format prints out an integer in a field of width 2. If it takes more than 2 characters to print out the integer it will print out two asterisks ** instead.
So the format with the repeat count will print out 2*9=18 integers. When the format is exhausted there are rules called format reversion that in this case will result in output advancing to the next line and the format being reused.
Finally, in free format code one can write the next line of code on the current one if the current statement is followed by a semicolon ;. Thus ;end puts the required end statement at the end of the program. Note that the introductory program statement, although good style, is optional.
The output of the program is as follows:
(-4,-4) (-4,-3) (-4,-2) (-4,-1) (-4, 0) (-4, 1) (-4, 2) (-4, 3) (-4, 4)
(-3,-4) (-3,-3) (-3,-2) (-3,-1) (-3, 0) (-3, 1) (-3, 2) (-3, 3) (-3, 4)
(-2,-4) (-2,-3) (-2,-2) (-2,-1) (-2, 0) (-2, 1) (-2, 2) (-2, 3) (-2, 4)
(-1,-4) (-1,-3) (-1,-2) (-1,-1) (-1, 0) (-1, 1) (-1, 2) (-1, 3) (-1, 4)
( 0,-4) ( 0,-3) ( 0,-2) ( 0,-1) ( 0, 0) ( 0, 1) ( 0, 2) ( 0, 3) ( 0, 4)
( 1,-4) ( 1,-3) ( 1,-2) ( 1,-1) ( 1, 0) ( 1, 1) ( 1, 2) ( 1, 3) ( 1, 4)
( 2,-4) ( 2,-3) ( 2,-2) ( 2,-1) ( 2, 0) ( 2, 1) ( 2, 2) ( 2, 3) ( 2, 4)
( 3,-4) ( 3,-3) ( 3,-2) ( 3,-1) ( 3, 0) ( 3, 1) ( 3, 2) ( 3, 3) ( 3, 4)
( 4,-4) ( 4,-3) ( 4,-2) ( 4,-1) ( 4, 0) ( 4, 1) ( 4, 2) ( 4, 3) ( 4, 4)
Looking at these results we might observe that within the diamond, |i|+|j|<=4 while outside, |i|+|j|>=5. Let's create a program to check this:
print'(9(L1))',[((abs(j)+abs(i)<5,j=-4,4),i=-4,4)];end
Similar to the last program, but now the still_more_stuff in the inner ac-implied-do, abs(j)+abs(i)<5 is a logical expression which asks 'is |j|+|i| less than 5?' The value of the expression will be .TRUE. or .FALSE., depending on the outcome of this test.
The L1 format is a logical I/O specifier that outputs T for .TRUE. or F for .FALSE..
Output of the program is as follows:
FFFFTFFFF
FFFTTTFFF
FFTTTTTFF
FTTTTTTTF
TTTTTTTTT
FTTTTTTTF
FFTTTTTFF
FFFTTTFFF
FFFFTFFFF
We can see the diamond but we need to convert to (spaces) and * (asterisks):
print'(9a)',merge('*',' ',[((abs(j)+abs(i)<5,j=-4,4),i=-4,4)]);end
And this does it! The merge function processes our logical array (the third argument) and everywhere a .TRUE. element is encountered, replaces it with an asterisk * (the first argument) while every .FALSE. element is replaced by a space (the second argument).
The resulting 81-element character array is printed out 9 elements at a time by the (9a) format string, resulting in the desired output. The whole program, although complex to write, was only 66 characters long :)
I propose this approach on implementation, because it gives you flexibility on the character string length to be printed.
program chardesign
implicit none
call print_diamond('*', 5, 1)
call print_diamond('()', 3, 3)
call print_diamond('.', 1, 4)
call print_diamond('0', 0, 3)
contains
subroutine print_diamond(str, depth, start)
character(*), intent(in) :: str
integer, intent(in) :: depth, start
character(len(str)) :: spc
integer :: i, span
spc = ''
span = start + (depth - 1) * 2
print '(a)', (repeat(spc, (span - i) / 2) // repeat(str, i), i = start, span, 2)
print '(a)', (repeat(spc, (span - i) / 2) // repeat(str, i), i = span - 2, start, -2)
end
end
This yields the following output:
*
***
*****
*******
*********
*******
*****
***
*
()()()
()()()()()
()()()()()()()
()()()()()
()()()
....
The task is to justify text within a certain width.
user inputs: Hello my name is Harrry. This is a sample text input that nobody
will enter.
output: What text width do you want?
user inputs: 15
output: |Hello my name|
|is Harrry. This|
|is a sample|
|text that|
|nobody will|
|enter. |
Basically, the line has to be 15 spaces wide including blank spaces. Also, if the next word in the line cant fit into 15, it will skip entirely. If there are multiple words in a line, it will try to distribute the spaces evenly between each word. See the line that says "Is a sample" for example.
I created a vector using getline(...) and all that and the entire text is saved in a vector. However, I'm kind of stuck on moving forward. I tried using multiple for loops, but I just cant seem to skip lines or even out the spacing at all.
Again, not looking or expecting anyone to solve this, but I'd appreciate it if you could guide me into the right direction in terms of logic/algorithm i should think about.
You should consider this Dynamic programming solution.
Split text into “good” lines
Since we don't know where we need to break the line for good justification, we start guessing where the break to be done to the paragraph. (That is we guess to determine whether we should break between two words and make the second word as start of the next line).
You notice something? We brutefore!
And note that if we can't find a word small enought to fit in the remaining space in the current line, we insert spaces inbetween the words in the current line. So, the space in the current line depends on the words that might go into the next or previous line. That's Dependency!
You are bruteforcing and you have dependency,there comes the DP!
Now lets define a state to identify the position on our path to solve this problem.
State: [i : j] ,which denotes line of words from ith word to jth word in the original sequence of words given as input.
Now, that you have state for the problem let us try to define how these states are related.
Since all our sub-problem states are just a pile of words, we can't just compare the words in each state and determine which one is better. Here better delineates to the use of line's width to hold maximum character and minimum spaces between the words in the particular line. So, we define a parameter, that would measure the goodness of the list of words from ith to jth words to make a line. (recall our definition of subproblem state). This is basically evaluating each of our subproblem state.
A simple comparison factor would be :
Define badness(i, j) for line of words[i : j].
For example,
Infinity if total length > page width,
else (page width − total length of words in current line)3
To make things even simple consider only suffix of the given text and apply this algorithm. This would reduce the DP table size from N*N to N.
So, For finishing lets make it clear what we want in DP terms,
subproblem = min. badness for suffix words[i :]
=⇒ No.of subproblems = Θ(n) where n = no of words
guessing = where to end first line, say i : j
=⇒ no. of choices for j = n − i = O(n)
recurrence relation between the subproblem:
• DP[i] = min(badness (i, j) + DP[j] for j in range (i + 1, n + 1))
• DP[n] = 0
=⇒ time per subproblem = Θ(n)
so, total time = Θ(n^2).
Also, I'll leave it to you how insert spaces between words after determining the words in each line.
Logic would be:
1) Put words in array
2) Loop though array of words
3) Count the number of chars in each word, and check until they are the text width or less (skip if more than textwidth). Remember the number of words that make up the total before going over 15 (example remember it took 3 words to get 9 characters, leaving space for 6 spaces)
4) Divide the number of spaces required by (number of words - 1)
5) Write those words, writing the same number of spaces each time.
Should give the desired effect I hope.
You obviously have some idea how to solve this, as you have already produced the sample output.
Perhaps re-solve your original problem writing down in words what you do in each step....
e.g.
Print text asking for sentence.
Take input
Split input into words.
Print text asking for width.
...
If you are stuck at any level, then expand the details into sub-steps.
I would look to separate the problem of working out a sequence of words which will fit onto a line.
Then how many spaces to add between each of the words.
Below is an example for printing one line after you find how many words to print and what is the starting word of the line.
std::cout << "|";
numOfSpaces = lineWidth - numOfCharsUsedByWords;
/*
* If we have three words |word1 word2 word3| in a line
* ideally the spaces to print between then are 1 less than the words
*/
int spaceChunks = numOfWordsInLine - 1;
/*
* Print the words from starting point to num of words
* you can print in a line
*/
for (j = 0; j < numOfWordsInLine; ++j) {
/*
* Calculation for the number of spaces to print
* after every word
*/
int spacesToPrint = 0;
if (spaceChunks <= 1) {
/*
* if one/two words then one
* chunk of spaces between so fill then up
*/
spacesToPrint = numOfSpaces;
} else {
/*
* Here its just segmenting a number into chunks
* example: segment 7 into 3 parts, will become 3 + 2 + 2
* 7 to 3 = (7%3) + (7/3) = 1 + 2 = 3
* 4 to 2 = (4%2) + (4/2) = 0 + 2 = 2
* 2 to 1 = (2%1) + (2/1) = 0 + 2 = 2
*/
spacesToPrint = (numOfSpaces % spaceChunks) + (numOfSpaces / spaceChunks);
}
numOfSpaces -= spacesToPrint;
spaceChunks--;
cout << words[j + lineStartIdx];
for (int space = 0; space < spacesToPrint; space++) {
std::cout << " ";
}
}
std::cout << "|" << std::endl;
Hope this code helps. Also you need to consider what happens if you set width less then the max word size.
I am creating a command-line minesweeper game which has a save and continue capability. My code generates a file called "save.txt" which stores the position of the mines and the cells that the player has opened. It is separated into two columns delimited by a space where the left column represents the row of the cell and the right column represents the column of the cell in the matrix generated by my code. The following is the contents of save.txt after a sample run:
3 7
3 9
5 7
6 7
8 4
Mine end
2 9
1 10
3 5
1 1
Cell open end
You may have noticed Mine end and Cell open end. These two basically separate the numbers into two groups where the first one is for the position of the mines and the latter is for the position of the cells opened by the player. I have created a code which generates an array for each column provided that the text file contains integers:
int arrayRow[9];
int arrayCol[9];
ifstream infile("save.txt");
int a, b;
while(infile >> a >> b){
for(int i = 0; i < 9; i++){
arrayRow[i] = a;
arrayCol[i] = b;
}
}
As you can see, this won't quite work with my text file since it contains non-integer text. Basically, I want to create four arrays: mineRow, mineCol, openedRow, and openedCol as per described by the first paragraph.
Aside from parsing the string yourself and doing string operations, you can probably redefine the file format to have a header. Then you can parse the once and keep everything in numbers. Namely:
Let the Header be the first two rows
Row 1 = mineRowLen mineColLen
Row 2 = openedRowLen openedColLen
Row 3...N = data
save.txt:
40 30
20 10
// rest of the entries
Then you just read 40 for the mineRow, 30 for mineCol, 20 for openedRow, 10 for openedCol since you know their lengths. This will be potentially harder to debug, but would allow you to hide the save state better to disallow easy modification of it.
You can read the file line by line.
If the line matches "Mine end" or "Cell open end", continue;
Else, split the line by space (" "), and fill the array.
In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the