You need to stop counting when you hit a null. A good way to do this is:Need some more C++ help.
I'm trying to make a program that takes in a user input, passes it into an array, counts the frequency of a given vowel within the string and then outputs that amount:
Code:#include <iostream> #include <string> using namespace std; int countVowels(int [], char []); int main() { char str[257]; int vowelCnt[5]; cout << "Enter a character string (max 256): "; cin.getline (str,257); countVowels(vowelCnt, str); cout << vowelCnt[0] << endl; cout << vowelCnt[1] << endl; cout << vowelCnt[2] << endl; cout << vowelCnt[3] << endl; cout << vowelCnt[4] << endl; } int countVowels(int counts[], char str[]) { int vowelCnt[5] = {0}; for (int i = 0; i < 257; i++) { if (str[i] == 'a' || str[i] == 'A') { vowelCnt[0]++; } else if (str[i] == 'e' || str[i] == 'E') { vowelCnt[1]++; } else if (str[i] == 'i' || str[i] == 'I') { vowelCnt[2]++; } else if (str[i] == 'o' || str[i] == 'O') { vowelCnt[3]++; } else if (str[i] == 'u' || str[i] == 'U') { vowelCnt[4]++; } } return *vowelCnt; }
Debugging shows that str is holding some pretty funky characters outside the user input, and vowelCnt is holding some pretty funky numbers.
Any ideas?
#include <iostream>
#include <string>
using namespace std;
int countVowels(int [], char []);
int main()
{
char str[257];
int vowelCnt[5] = {0, 0, 0, 0, 0};
cout << "Enter a character string (max 256): ";
cin.getline (str,257);
countVowels(vowelCnt, str);
cout << vowelCnt[0] << endl;
cout << vowelCnt[1] << endl;
cout << vowelCnt[2] << endl;
cout << vowelCnt[3] << endl;
cout << vowelCnt[4] << endl;
}
int countVowels(int counts[], char str[])
{
int vowelCnt[5];
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == 'a' || str[i] == 'A') {
vowelCnt[0]++;
}
else if (str[i] == 'e' || str[i] == 'E') {
vowelCnt[1]++;
}
else if (str[i] == 'i' || str[i] == 'I') {
vowelCnt[2]++;
}
else if (str[i] == 'o' || str[i] == 'O') {
vowelCnt[3]++;
}
else if (str[i] == 'u' || str[i] == 'U') {
vowelCnt[4]++;
}
return *vowelCnt;
}
}
def find_closest(botx,boty,board):
current = 0
bestxy=0
difference = 0
best = 500
for i in board:
if "d" in i:
for x in i:
if x == "d":
current = [i.index(x),board.index(i)]
difference =abs(current[0]-botx) + abs(current[1]-boty)
if difference < best:
best = difference
bestxy = [i.index(x),board.index(i)]
return bestxy
def next_move(posr, posc, board):
target = find_closest(posr,posc,board) #bestxy
if board[posr][posc]== "d":
print "CLEAN"
return
if posr < target[0]:
print "RIGHT"
return
if posc > target[1]:
print "UP"
return
if posr > target[0]:
print "LEFT"
return
if posc < target[1]:
print "DOWN"
return
How long did it take most of you to understand Java? I'm taking a beginner's course, but it's still not clicking to me. I'm having a hard time doing assignments that consist of either constructors or loops.
C++ has perfectly good strings, so just sticking to them instead of the C-style char arrays would make your life a ton easier. Also, using the std::map data structure would get rid of pretty much all the repetitive code. Below is a working C++11 solution; needs small changes if you have to use C++98.Need some more C++ help.
I'm trying to make a program that takes in a user input, passes it into an array, counts the frequency of a given vowel within the string and then outputs that amount:
string s;
getline(cin, s);
// <- cut string size down to 256 here, if you actually wanted to do that
auto m = map<char, unsigned>();
// count chars into the map
for (char c : s) {
m[c] += 1;
}
auto vowels = {'a', 'e', 'i', 'o', 'u'};
// print the vowel counts
for (char c : vowels) {
cout << c << ": " << (m[c] + m[(char)toupper(c)]) << endl;
}
C++ has perfectly good strings, so just sticking to them instead of the C-style char arrays would make your life a ton easier. Also, using the std::map data structure would get rid of pretty much all the repetitive code. Below is a working C++11 solution; needs small changes if you have to use C++98.
Even if you don't use a map, you can iterate the characters this way. Another way to get the character counts would be to use the std::count or std::count_if algorithms, but it's slightly more work than this.Code:string s; getline(cin, s); // <- cut string size down to 256 here, if you actually wanted to do that auto m = map<char, unsigned>(); // count chars into the map for (char c : s) { m[c] += 1; } auto vowels = {'a', 'e', 'i', 'o', 'u'}; // print the vowel counts for (char c : vowels) { cout << c << ": " << (m[c] + m[(char)toupper(c)]) << endl; }
Something like this?
Code:#include <iostream> #include <string> using namespace std; int countVowels(int [], char []); int main() { char str[257]; int vowelCnt[5] = {0, 0, 0, 0, 0}; cout << "Enter a character string (max 256): "; cin.getline (str,257); countVowels(vowelCnt, str); cout << vowelCnt[0] << endl; cout << vowelCnt[1] << endl; cout << vowelCnt[2] << endl; cout << vowelCnt[3] << endl; cout << vowelCnt[4] << endl; } int countVowels(int counts[], char str[]) { int vowelCnt[5]; for (int i = 0; str[i] != '\0'; i++) { if (str[i] == 'a' || str[i] == 'A') { vowelCnt[0]++; } else if (str[i] == 'e' || str[i] == 'E') { vowelCnt[1]++; } else if (str[i] == 'i' || str[i] == 'I') { vowelCnt[2]++; } else if (str[i] == 'o' || str[i] == 'O') { vowelCnt[3]++; } else if (str[i] == 'u' || str[i] == 'U') { vowelCnt[4]++; } return *vowelCnt; } }
so status quo?Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah." It makes things infinitely more difficult. To make matters worst, he doesn't tailor the program to stuff we've learned from the book (I'd say from lecture, but the man simply reads off the power point that came with the textbook, providing no further examples), and often times in his specifics, asks for stuff where we're basically forced to learn outside the text. To make matters worst, he was out sick this last week, and is sticking to his policy of not answering questions on homework or labs (what kind of policy is that?). So we're basically left with our dicks in our hands, learning the language on our own efforts Lol.
I'm definitely listening to Ratemyprofessor next quarter....
Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah." It makes things infinitely more difficult. To make matters worst, he doesn't tailor the program to stuff we've learned from the book (I'd say from lecture, but the man simply reads off the power point that came with the textbook, providing no further examples), and often times in his specifics, asks for stuff where we're basically forced to learn outside the text. To make matters worst, he was out sick this last week, and is sticking to his policy of not answering questions on homework or labs (what kind of policy is that?). So we're basically left with our dicks in our hands, learning the language on our own efforts Lol.
I'm definitely listening to Ratemyprofessor next quarter....
Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
i don't know how far along you are in your studies, but as painful as working with c character arrays are, i think it's worth feeling that pain at least once. it's a hassle, but like calvin's father says: "it builds character". but really, it does give you a deeper understanding into the etymology of strings and a greater appreciation for their modern implementations.
i don't know how far along you are in your studies, but as painful as working with c character arrays are, i think it's worth feeling that pain at least once. it's a hassle, but like calvin's father says: "it builds character". but really, it does give you a deeper understanding into the etymology of strings and a greater appreciation for their modern implementations.
on the other hand, if you're forced to do this as a senior after already becoming intimately familiar with c strings, you are in the right for being pissed. either way, get a good grade and then never use them again. make a dartboard with your prof's face in the center.
Also the return statement is not being used at all, but in fact makes the function end after the first iteration of the for loop.You're passing vowelCnt into the function countVowels and then not using it at all, instead opting to use another declaration of vowelCnt that has nothing in it.
In countVowels change vowelCnt to count and see what you get.
Also the return statement is not being used at all, but in fact makes the function end after the first iteration of the for loop.
public abstract class Vehicle {
private int wheels;
private String extColor;
private String name;
private int year;
protected Vehicle() {
}
protected Vehicle(int vehWheels, String extColor, String vehName, int vehYear) {
this.wheels = vehWheels;
this.extColor = extColor;
this.name = vehName;
this.year = vehYear;
}
public abstract void getColor();
public abstract void getDesc();
public int getWheels() {
return wheels;
}
public String getExtColor() {
return extColor;
}
public String getName() {
return name;
}
public int getYear() {
return year;
}
public void setWheels(int wheels) {
this.wheels = wheels;
}
public void setExtColor(String extColor) {
this.extColor = extColor;
}
public void setName(String name) {
this.name = name;
}
public void setYear(int year) {
this.year = year;
}
}
public class Car extends Vehicle {
private int maxMPH;
private String intColor;
public void getColor() {
System.out.println("This car is " + getExtColor() + " with " + intColor + " interior.");
}
public void getDesc() {
System.out.println("The full description of this car is as follows:\n" + getYear() + " " + getName() + ".\n"
+ getExtColor() + " exterior with " + intColor + " interior.\n" + "Max speed of " + maxMPH + "mph on "
+ getWheels() + " wheels");
}
public Car(int vehWheels, String extColor, String vehName, int vehYear, int vehMPH, String vehIntColor) {
setWheels(vehWheels);
setExtColor(extColor);
setName(vehName);
setYear(vehYear);
maxMPH = vehMPH;
intColor = vehIntColor;
}
public static void main(String[] args) {
Vehicle car1 = new Car(4, "Black", "Volkswagen", 2001, 135, "Tan");
car1.getColor();
car1.getDesc();
}
}
That looks pretty much right, although the assignment would make more sense if the print function was part of the abstract class and the implementations of the information functions were up to the extending classes.
The beauty of abstract classes is that you could run that program for ten years, and then realise that bikes exist, add a Bike class that extends Vehicle, and stick it in an array of Vehicles together with Cars and your program would still work. There's really no deeper realisation about what abstract classes are if you get everything you're doing in the code you've posted.
Another nice thing that courses tend to miss is that you can absolutely extend non-abstract (concrete?) classes too for basically the same benefit. The abstract methods are the only difference.
You probably shouldn't have "Wheels" as a part of an abstract vehicle class, given that some vehicles do not have wheels - e.g. a boat, a snowmobile, a hanglider, or a tank.
Some people might say "well, just create those as vehicles with zero wheels", but personally I think abstract classes work better when they describe only what is essential to them, rather than trying to anticipate all of the possible child classes and adding methods that are only meant for a subset of children.
An alternative would be to create another abstract class, WheeledVehicle, that inherits from Vehicle, then have Car inherit from that. Of course you also don't want to go overboard with abstraction since it can hurt performance, but then again this is Java so who cares.
The function prototype only constrains what is supposed to go in and out. If you haven't been given additional constraints, you can always convert the data inside the function to a form that's easier to process. The core of the function could be written almost exactly like I showed earlier.Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah."
...
Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
Well okay, I thought I got it, but I don't get it after all. Unit tests are just weird. I pretty much have to create constructors or factories that take every single variable, or have setters for every variable, so I can mock them out and have precise tests. But that's silly (especially for immutable objects), I'd rather just stick some print line somewhere to confirm things work. I don't think my normal thinking process is that different from doing unit tests first either because I'm already doing it internally for almost everything.
Well okay, I thought I got it, but I don't get it after all. Unit tests are just weird. I pretty much have to create constructors or factories that take every single variable, or have setters for every variable, so I can mock them out and have precise tests. But that's silly (especially for immutable objects), I'd rather just stick some print line somewhere to confirm things work. I don't think my normal thinking process is that different from doing unit tests first either because I'm already doing it internally for almost everything.
From what I've read I could really use integration tests but eh.
I benefited greatly by going through a pseudocode-based programming logic and design book with very understandable (and concise) explanations when I first started programming. My first language was Python but this didn't matter in the grand scheme of things. I suppose because I read this book, I didn't have a problem going over to Java ( in fact, the book came with language companion documents for java, which I used). I read this book because of a class I took that didn't count toward my major and wasn't required.
Maybe it should be. This was years ago and I haven't even taken Programming 1 yet (due to Calculus), but I couldn't imagine going into it cold and having to learn all of that stuff within 3 1/2 months.
I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.Unit tests are pretty much a necessity for automatic builds. As it would happen, most build tools have support for the common unit testing frameworks. By putting in unit tests, you can pretty much know if a change broke the build.
I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.
You mean that the automatic building builds the unit tests automatically too? Because I was weighting in the effort it takes to write those.
Man, I understand you, and I think that's what I've been trying to do, but I still can't wrap my head around it. I think it comes down to these things appearing a lot more useful with a long term POV, which I super don't have, so I might not see the point until it screws me over not doing it.Read through the first part of this reply. The purpose of unit testing is to test the public api. You should not be checking individual values unless they are return results from a public function. You should never be checking internal state of a method or class.
What is the name or author of the book?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="StyleSheet" href="style.css" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
<title>Random</title>
</head>
<body>
<h1>Random</h1>
<p>Write tables width and length.</p>
<form action="">
<fieldset>
<p><label>Width <input type="text" name="width" /></label></p>
<p><label>Length <input type="text" name="height" /></label></p>
</fieldset>
<p><input type="submit" value="Make randomized table" /></p>
</form>
</body>
</html>
I wouldn't say always. Mocks are primarily used during unit testing to verify things that are not really a part of the public interface of a class. They're used to test the interactions between the class under test and it's dependencies.Read through the first part of this reply. The purpose of unit testing is to test the public api. You should not be checking individual values unless they are return results from a public function. You should never be checking internal state of a method or class.
That sounds a bit messy. Testing as you go ensures that every bit of code has at least two users: the original reason why you wrote it, and the test. In that way, testing helps prod you towards more modular, reusable designs.Not every variable, but the variables that load data from files all need to be mocked (even if I wanted to, trying to load files through JUnit in LibGDX just gives a null error). And I don't know if I designed things wrong or something, but those variables are referenced almost everywhere in the project, and most of them are created inside the objects and not passed through constructors because it would be a huge mess otherwise.
There are some things I can test pretty cleanly but they're kinda scarce, and they're mostly things that would be easily wrong on screen if they ever broke in the future refactoring.
I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.
Could someone that is familiar with page tables explain to me what to do if a page table has more entries than there are frames in physical memory? I'm trying to just work this example out for this single page table sim I'm working on and its been a rather busy week and my brain is fried.
I take in 32 bit addresses and am given that the frame size is 1KB and physical memory is 1GB. The number of frames is 1GB/1KB = 1MB and the number of page table entries is 2^(32-offset) = 4MB. How do I deal with the page table having more entries than there are frames of memory? Do I limit the page entries to 1MB?
#ifndef QUEUE_H_
#define QUEUE_H_
using namespace std;
#include <cstdlib>
#include <iostream>
#include <queue>
#include <list>
#include<string>
//priority_queue<int> p1; // a priority queue of integers
// a priority queue of points with left-to-right order
struct patient{
string name;
int time;
bool islifeThreat;
};
class PriorityQueue { // priority-queue interface
public:
PriorityQueue();
int size(); // number of elements
bool empty(); // is the queue empty?
void insert(patient p); // insert element
patient min(); // minimum element
void removeMin(); // remove minimum
virtual ~PriorityQueue(); // deconstructor
private:
list<patient> patientList; // priority queue contents
//C isLess; // less-than comparator
};
#endif /* QUEUE_H_ */
Could someone that is familiar with page tables explain to me what to do if a page table has more entries than there are frames in physical memory? I'm trying to just work this example out for this single page table sim I'm working on and its been a rather busy week and my brain is fried.
I take in 32 bit addresses and am given that the frame size is 1KB and physical memory is 1GB. The number of frames is 1GB/1KB = 1MB and the number of page table entries is 2^(32-offset) = 4MB. How do I deal with the page table having more entries than there are frames of memory? Do I limit the page entries to 1MB?
The third phase of Nachos is to investigate the use of caching. In this assignment we use caching for two purposes. First, we use a software-managed translation lookaside buffer (TLB) as a cache for page tables to provide the illusion of fast access to virtual page translation over a large address address space. Second, we use memory as a cache for disk, to provide the abstraction of an (almost) unlimited virtual memory size, with performance close to that provided by physical memory. We provide no new code for this assignment (the only change is that you need to compile with the '-DVM -DUSE_TLB' flags - which is already set if you compile from the vm directory); your job is to write the code to manage the TLB and to implement virtual memory. You can edit files in the userprog directory, but you must compile and run Nachos from the vm directory.
Page tables were used in assignment 2 to simplify memory allocation and to isolate failures from one address space from affecting other programs. For this assignment, the hardware knows nothing about page tables. Instead it only deals with a software-loaded cache of page table entries, called the TLB. On almost all modern processor architectures, a TLB is used to speed address translation. Given a memory address (an instruction to fetch, or data to load or store), the processor first looks in the TLB to determine if the mapping of virtual page to physical page is already known. If so (a TLB 'hit'), the translation can be done quickly. But if the mapping is not in the TLB (a TLB 'miss'), page tables and/or segment tables are used to determine the correct translation. On several architectures, including Nachos, the DEC MIPS and the HP Snakes, a 'TLB miss' simply causes a trap to the OS kernel, which does the translation, loads the mapping into the TLB and re-starts the program. This allows the OS kernel to choose whatever combination of page table, segment table, inverted page table, etc., it needs to do the translation (which is what you get to do). On systems without software-managed TLB's, the hardware does the same thing as the software, but in this case, the hardware must specify the exact format for page and segment tables. Thus, software managed TLB's are more flexible, at a cost of being somewhat slower for handling TLB misses. If TLB misses are very infrequent, the performance impact of software managed TLB's can be minimal.
The illusion of unlimited memory is provided by the operating system by using main memory as a cache for the disk. For this assignment, page translation allows us the flexibility to get pages from disk as they are needed. Each entry in the TLB has a valid bit: if the valid bit is set, the virtual page is in memory. If the valid bit is clear or if the virtual page is not found in the TLB, a software page table is needed to tell whether the page is in memory (with the TLB to be loaded with the translation), or the page must be brought in from disk. In addition, the hardware sets the use bit in the TLB entry whenever a page is referenced and the dirty bit whenever the page is modified.
When a program references a page that is not in the TLB, the hardware generates a TLB exception, trapping to the kernel (eventually reaching the exceptionHandler() function). The operating system kernel then checks its own page table. If the page is not in memory, it reads the page in from disk, sets the page table entry to point to the new page, sets the TLB correctly, and then resumes the execution of the user program. Of course, the kernel must first find space in memory for the incoming page, potentially writing some other page back to disk, if it has been modified.
As with any caching system, performance depends on the policy used to decide which things are kept in memory and which are only stored on disk. On a page fault, the kernel must decide which page to replace; ideally, it will throw out a page that will not be referenced for a long time, keeping pages in memory those that are soon to be referenced
You need a space before <string>Hey guys I decided to finally do some programming assignments at home. I put eclipse on an external hard drive. I seem to be having some issues with my includes? I'm trying to make a priority queue.
...
I'm using a mac right now if that helps any.
If you're really new to JavaScript, it's going to be quite difficult. If you have to create a table, you use document.createElement('table') and use the same method to make TRs and TDs -- if you need to actually add that. To set text on an element you can use myElement.appendChild(document.createTextNode('some text')). I don't know if you can use textContent or innerText or innerHTML just to set text, which would make it a bit easier.Hey! First timer on this topic and I really need simple javascript help, hope someone can help me!
So we were given this simple HTML code
And what our task is:
1. Can't touch HTML code, everything has to be done in javascript and css files
2. Have to be able to give tables height and width and then then when button is pressed it will make table with those width and height.
3. Table should get filled with random numbers
4. no INNER.html stuff... Every example online uses that
I'll really need to get this task done, need the course points badly. Thanks so much if someone can shed even tiny bit of light into this, our teacher really sucks and his lectures are terrible...
Any tips on how to get control of the button for example and make it to do something in javascript?
// create a table
var table = ???;
// set the values to random numbers
???
// find the submit button
var submitButton = ???;
submitButton.onclick = function () {
// set table's height and width to the values in the inputs
table.height = ???; // find the height input and get its value
table.width = ???; // similar situation
// you really only need to do this once
// wrap it in an if to test if the table is already on the page, if you want
document.body.appendChild(table);
};
You need a space before <string>
Fixed that. the 'std' in namespace is showing an error and all of my includes are showinf errors. any reason why that might be?
string a;
std::string a;
Guys, I need good programming music. What do you all listen to when in the zone?
Guys, I need good programming music. What do you all listen to when in the zone?
Guys, I need good programming music. What do you all listen to when in the zone?
Guys, I need good programming music. What do you all listen to when in the zone?
I find video game soundtracks are often really good for me. Probably because they're generally meant to be background music, so they aren't too distracting for me. I can't program to anything with lyrics...
Speaking of, I find that regardless of what music I'm listening to there are times where I have to mute everything. Generally when I'm focusing on a really tricky or complicated problem. Anybody else experience this, or are you able to tune out the music when you need 100% concentration?
Additional commentary:As a side note, it is usually considered bad practice to have a using directive in a header file. I would suggest that you remove it and use fully qualifed declarations.
That is
Code:string a;
becomes
Code:std::string a;
I don't know if that will fix your problem, but it's a good idea to do it either way.
Since you mention that all of your include statements are showing errors, the most likely issue is that you probably do not have the path to your standard libraries set in Eclipse.