mrnutty 761 Senior Poster

Use a map or a set

mrnutty 761 Senior Poster

I think your printing loop is incorrect, try doing this :

list<nonZero>::iterator j;
	list< list<nonZero> >::iterator i;
	for(i = rows.begin(); i != rows.end(); i++)
	{
		for(j = i->begin();j != i->end(); j++)
		{
			cout<<(*j).getColumn()<<" "<<(*j).getValue()<<" ";
		}
		cout<<endl;
	}
comSysStudent commented: Helped me out a lot +2
mrnutty 761 Senior Poster

If ur on windows, use Sleep(milliseconds) located on windows.h. If ur on linux use sleep(seconds) located on unistd.h

mrnutty 761 Senior Poster

I think OP is analyzing it way too much. there is no reason why you should rewrite the statement again. Its perfectly clear with its intentions. I think the problem is that you are confused about the theory. You need to just get more practice in first. Then the theory will make more sense because you actually have an concrete understanding of whats being said in the sentence. So for right now, don't waste your time rewriting it. There is no point. Use that free time to go play with friends or something.

mrnutty 761 Senior Poster

For the zero problem you can have a cutoff value. Example :

float bandwidthCuttoff(const float value, const float width = 0.000001f){
 if(-width <= value && value <= width) return 0.0f;
 else return value;
}

then you just pass the j (imaginary part) to this function to make a cut if needed.

mrnutty 761 Senior Poster

Another approach is to create your own namespace :

#include <iostream>
using namespace std;

namespace Util{
 template<typename T>
 T& max(const T& lhs, const T& rhs){ return lhs < rhs ? rhs : lhs ; }
};
int main(){
 cout << Util::max(1,2) << endl;
}
gerard4143 commented: Like your simple solution +5
mrnutty 761 Senior Poster

There is no such things as stackType use std::stack

JamieLynnSEO commented: Mhm. +1
mrnutty 761 Senior Poster

since i study alone and my code starts to be more big and more chaotic
i have some questions that maybe will sound silly to more but i have to ask someone.

As with most things, you need to study and work hard yourself. There isn't going to be guru created to make you the best, you have to be your own guru.

1- its better to declare global only the constant variables?
First of all, you should try to avoid global variables as much as possible. If you have no choice then you should encapsulate them.

2- should i create manyyyyy functions small and do simple small tasks each one?

Yes and no. Don't over over do it. But generally, make each function have specific small task. If possible, reduce the function into more function. But be aware, there is always some line, which is subjective.

3- should i let functions take many arguments like that:
Probably not. Try to break the function into sub-function, or maybe even encapsulate things in a struct and pass that struct. Do what make sense.

4- comments!where i should put them?right of each line?or at top of a function or loop?do i need to comment everything?i tried at right of each line and was too messed with many comments

This is a style issue. First put comments where you need it. Don't put comments in areas where the code explains what …

mrnutty 761 Senior Poster

Just a quick explanation on Abstract Data Type(ADT)

WHO: Abstract Data Type
WHAT: Abstract Data Type are data-type that combines the common functionalities from different related objects into one package, so that those different but related object's interface can inherit from the ADT thus making it more flexible and and less coding for the programmer.
WHERE: Anywhere, when you code, in your life wherever applicable.
WHEN : Use it when you want to generalize a design. When you have many objects that have similar functionalities, you can Abstract the common functionalities into one class, and have the other objects inherit from them.
WHY You would create ADT for numerous reasons. First it generally leads to a flexible design if designed well. Second its less coding for the programmer. Third its more reuseability . Fourth, it leads to easier maintenance. And Fifth, it creates the possibility of polymorphism.

Here is a quick example :

//abstract data type
struct Object{
 virtual std::string toString()const = 0;
};
struct Int : Object{
 int val;
 std::string toString()const{ return boost::lexical_cast<std::string>(val); }
 Int(int iVal) : i(iVal){}
};
struct Float: Object{
 float val;
 std::string toString()const{ return boost::lexical_cast<std::string>(val); }
 Float(float fVal) : val(fVal){}
};
int main(){
 Int i(0);
 Float f(123.456);
 std::string strNum = i.toString() + f.toString();

}
ddanbe commented: Nice answer! +15
mrnutty 761 Senior Poster

- First you should be using std::vectors if possible.
- Second returning the array is kind of bad OOP, since your encapsulation decreases.

Instead consider providing mechanism to accesses the coefficients. For example.

class Polynomial{
private:
 float coefficients[10];
 float exponents[10];
public:
 //...
 const float coefficientAt(int i )const;
 const float exponentsAt(int i)const;
};

or something of that nature. But you would be probably better off using std::vector if possible.

Or consider providing iterator-like interface. For example :

class Polynomial{
private:
 float coefficients[10];
 float exponent[10];
public:
//...
 const float* coefficientsBegin()const { return coefficients; }
 const float* coefficientsEnd()const{ return coefficients + 10; }
//...
}
Red Goose commented: Good adivce. +1
mrnutty 761 Senior Poster

You can't rely on people to help you all the time. The point of this project is not only for you to be able to do large complex project but also research and do stuff on your own. This is the internet. There are plenty of sources. First you need to learn a little about speech recognition. You need to get out there and look for sources. Sources that helps you. So go and work hard.

mrnutty 761 Senior Poster

I don't know if there is a solution manual for it( google it), but you can post the problem and we'll be happy to solve it for you, provided that you attempted and solved the problem already, if not then we can guide you to the solutions.

mrnutty 761 Senior Poster
averaged[i];
if(i>highest)

You probably want

if( averaged[i] > averaged[highest] ){ highest = i; }
mrnutty 761 Senior Poster

Since they are raw pointers you would have to deallocate each pointer manually. If you want to use something like m_vPopulation2 = m_vParentPop2 then you should instead use smart pointers instead of raw pointers.

If both of the vectors are the same size then you can do this :

for(int i = 0; m_vParentPop2.size(); ++i){
  DNA* elem = m_vPopulation2[i];
  m_vPopulation2[i] = new DNA(*(m_vParentPop2[i]); //make a copy of DNA
  delete elem; //delete the old element
}
mrnutty 761 Senior Poster

>>Note: Im planning on using this with a Message box

If so then you will need to convert the variable to a string if its not already. A handy tool is to use something like the following :

template<typename ReturnType, typename InputType>
ReturnType convertTo(const InputType& input){
 std::stringstream stream; //#include <sstream> for this
 ReturnType var = ReturnType();
 if(! (stream << input && stream >> var ) ) throw std::exception("Conversion failed");

 return var;
}
//...
//use like this
float f = 3.14f;
string str = "PI = " + convertTo<string>(f);
mrnutty 761 Senior Poster

To polish it, you can combine the words[] and numbers[] into one std::pair<string,int>;
And your search in GetNumber could be just, numbers[ words.find_first_of(number) ] , but be careful about error checking. And make the parameters const-reference.

This code

std::string tempString;
	size_t size = sentence.size();
	for (size_t i = 0; i < size; i++)
	{
		if (sentence[i] == ' ')
		{
			parts.push_back(tempString);
			tempString.clear();
		}
		else
		{
			tempString += sentence[i];
		}
	}

should be a function by itself using stringstream:

std::vector<string> splitBySpace(const std::string& src){
 std::vector<string> result;
 stringstream stream;
 string word;
 stream << src;
 while( src >> word ){ result.push_back(word ); }
 return result;
}

Similarly there are more parts to ConvertTextToNumber that you can split into more functions.

mrnutty 761 Senior Poster

make getAverage a static function

mrnutty 761 Senior Poster

>>>string str; cin >> str
You might consider using getline(cin,str) just in case the user might try to enter something like 05 : 25 : 60 . Notice the spaces.

mrnutty 761 Senior Poster

Just a wild guess at what you want but a negative number can be represented in a string simply by the negation operator like so : string negativeFive = "-5" .
Then if you want to convert it back, then you can check if negativeFive[0] == '-' and if it is then start from position 1 and use the usual conversion from a positive string number to a integer. And then depending on whether we started at position 1 or not, you can negate the result.

mrnutty 761 Senior Poster

I want you to name one thing that you really want and is plausible( not some ridiculous wish) and fair, and tell me whats stopping you from getting it? And then I want you to
go and get it!!! Fight through the walls and barriers and grab the prize!!!

Yesterday, I had this wakeup call a couple of days ago, and now I am acting upon it. I am going for what I want in life and fighting through every obstacle thats in the way to get the prize. A few days I realized that I still want to be with my ex. So yesterday I acted upon it and now slowly but surely, I'm getting her! A couple of days ago, I wanted to write algorithms for my professor instead of creating a GUI for his programs, and now I'm getting it. A couple of days ago, I wanted to be more confident, and now I am! I don't know what compelled me to spread the word, but I want you guys to know that you can achieve. You can get what you want in life. All you have to do is that initial starting push. Then you'll be well on your way. I want you guys to pick one thing you want today, and starting going for it tomorrow! Don't let this be a moment where tomorrow or a few days from now you forget about it. Come back and re-read this post. Go talk to …

Sulley's Boo commented: Thanks for the encouragement! +0
kvprajapati commented: :) really inspired! +0
mrnutty 761 Senior Poster

Truthfully, that gives absolutely no advantage, bloats code, makes it hard to read, and is probably slower( although not noticeably ). And as your friend suggest, and your ego denied, its just bad coding. Drop this like a bad habit.

mrnutty 761 Senior Poster

As said earlier, you aren't using the template correctly. In your "SetName", if a template instantiation is made of type double, then you will have a compiler error, because you can't assign a double to a string.

mrnutty 761 Senior Poster

Programming is logical. So you need to train your self how to think logically. Some people compare programming with math because they both require perfect logic. So my suggestion is to change your mind of thought. Train yourself to think more logically. One way to do this, is to do simple practice problems. Not only it trains your mind to think logically but it also gives you experience coding. And if you don't have the passion to practice and to get better each day, then you should probably switch majors.

eman 22 commented: good comment +0
mrnutty 761 Senior Poster
for(int i=1; i<N; i++)
for(int j=1; j<N; j++)
for(int k=1; k <= i*j*log(j); k*=2) x=i+j+k;

Your first for-loop runs at most N times.
And for each i, it runs at most N times,
and for each j, it runs at most i*j*log(j) times

Notice i and j is always less than N, thus i*j*log(j) <= N*N*log(N)

Thus the total runtime or Big-Oh of you loop is : (N)*(N)*(N*N*log(N)) = N^4*log(N)

mrnutty 761 Senior Poster

@OP: Usually you should avoid the usage of static keyword. To further explain the problem consider what happens here :

int x = 10;
int &y = x;
y = 20; //x = 20 as well

Since y is a reference to x. Changing y will also change x. Basically, y is another name for x.

Now what happens when x is not valid, meaning when it goes out of scope? For example
this function shows such a case:

int& getFive(){
 int x = 5;
 return x;
}

and call it like so int& y = getFive(); . Now just like in the other y is a reference to x. But this time x is not valid. x is not valid because it goes out of scope and the compiler destroys it. Here is a psuedo-sequence of what happens in the above call to getFive();
1) y is declared as a reference to getFive();
2) getFive() gets executed
3) Inside getFive() the variable x gets created and initialized to 5. Since x is not declared static, you tell the compiler that it goes out of scope at the end of the function and thus should get destroyed and free the memory it occupies.
4) Now you try to return x. But the function says that return x as a reference so the compiler possibly tries to return x as a reference but you told the compiler to destroy x when …

mrnutty 761 Senior Poster

You need to also make sure its on fixed format. Here is an example :

void printDollars(const float amount){
 //save old states
 std::ios_base::fmtflags oldFlg = cout.setf(std::ios::fixed, std::ios::floatfield);
 int oldPrecision = cout.precision(2);

 cout << "$ " << amount << endl;

 //reset old states
 cout.setf(oldFlg);
 cout.precision(oldPrecision);

}
mrnutty 761 Senior Poster

Check this site out. It shows you many bit hacking solutions. If you program in a closed, restricted and limited programming hardware, they come to use.

anishakaul commented: Very helpful link. +2
Onlineshade commented: Good post. +0
mrnutty 761 Senior Poster

I will tell you int's will be faster than floats/doubles. And doubles will be faster than floats. But to answer your question yes, you can use ctime header. Here is an example:

#include <iostream>
#include <ctime>

int main(){
  time_t startTime = clock();
   /* code to test goes here */
  time_t endTime = clock();

  cout << "Difference in time(milliseconds) : " << endTime - startTime << endl;
}
matthewkeating commented: Thank you! Awesome answer. +1
mrnutty 761 Senior Poster

No the point is to work with each digit in the string, not convert the string into a double..

mrnutty 761 Senior Poster

They all suck and have their weakness. So there isn't one.

mrnutty 761 Senior Poster

>> I want to get some feedback on my code to facilitate improvement.

Drop the array_begin and array_end pointer stuff. Use the [] operator instead on the passed in array. As pointed out, forget about register keyword. BubbleSort is slow already so drop the early exit boolean stuff and just simplify it all. That way you have at least something thats readable and just as slow-ish.

mrnutty 761 Senior Poster

This is what you want :

string myName = "josh";
string myBrotherName = "tommy";
string input;

cout << "Enter a name : ";
cin >> input;

if(input == myName){
 cout << "Welcome admin\n";
}
else if(input == myBrotherName){
 cout  << "Welcome guest\n";
}
else cout << "Invalid user\n";
mrnutty 761 Senior Poster

Just use the C++ random_shuffle, its been tested for its distribution so its most likely good enough.

mrnutty 761 Senior Poster

This code test t2 = 50; is the same as test t2 = test(50); and this code test t3; is the same as test t3 = test();

mrnutty 761 Senior Poster

should sortPrint first sort the vector and then print it out?

Do something like this :

void sortPrint(std::vector<int> v){
 //sort v using your sorting algorithm?
 //print out each element in v;
}
mrnutty 761 Senior Poster

sort the vector inside the sortPrint function and then print it?

mrnutty 761 Senior Poster

How about a skeleton :

string uniqify(const std::string& source,int currentLocation){
 if(source.length() <= 1) return source;
 else{/*code here */}
}
string string_clean(const std::string& str){
 return uniqify(source,0);
}
mrnutty 761 Senior Poster

Try using this to hash strings:

unsigned long hash(unsigned char *str){
        unsigned long hash = 5381;
        int c;

        while (c = *str++)
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

        return hash;
    }

Then you can incorporate this for the person's last and first name. The algorithm above was found in google.

tylerjgarland commented: While I understand his answer, the google sarcasm is not helpful. I understood hashcode, I just needed help fitting it into a closed array. +0
mrnutty 761 Senior Poster

I'll do it for $35 an hour?

jonsca commented: Cheap! +5
mrnutty 761 Senior Poster

Also, just for giggle, I calculated that this function : 1/2n^2-1/2n+1 gives the number of sequence that sums to a number n. Try it out and see if its correct. I give no guarantees.

mrnutty 761 Senior Poster

Yes I can. But instead of giving you the answer. I am going to help and guide you through this long and tough journey to find the number of magical sevens in a given integer.

So to start, do you have any ideas? Does not have to be in code, just basic ideas?

mrnutty 761 Senior Poster

Again more corrections :

while (read>>Name)
    {
        l.push_back(Name);
    {
//...

  while(temp !=l.end())
    {
       cout<<*temp<< " ";
    {

For loops you use the curly braces not the parenthesis.

mrnutty 761 Senior Poster

Correction:

while(iter !=aList.end())
    {
        if( *max<*iter)
            max=iter;
        iter++;
        //return max;
    }
 return max;
mrnutty 761 Senior Poster

Discard the char* and use std::string

mrnutty 761 Senior Poster

You cannot as of right now, seperate the template definition from its implementation. They both need to go in the same file.

mrnutty 761 Senior Poster

One way is to do the following:

void display(float average){
 cout.precision(2);
 cout << average << endl;
}

Or you can truncate the number to 2 decimal place like so :

void display(float average){
 cout << truncate(average,2) << endl;
}
//use integer division
float truncate(float num,int decimalPlaces){
 int factor = std::pow(10,decimalPlaces); 
 int tmp = num * factor;
 return tmp/float(factor);
}
mrnutty 761 Senior Poster

the search function takes in 4 arguments not five.

What you want is something like this:

//returns true if source contains target with case ignored
bool no_case_compare(const string& source, const string& target){
 string srcCpy(source.size(),0);
 string targetCpy(target.size(),0);
 std::transform(source.begin(),source.end(),srcCpy.begin(),tolower);
 std::transform(target.begin(),target.end(),targetCpy.begin(),tolower);
 return srcCpy.find(targetCpy) != string::npos;
}
mrnutty 761 Senior Poster

Psuedo-Code

for i = 1 To N
 if(N % i == 0) printFactor(i);
mrnutty 761 Senior Poster

change this calculation function_one(calculation addition) to this calculation function_one(calculation& addition) and realize the difference.

mrnutty 761 Senior Poster

@OP: Forget you ever saw that code. Its useless.This insertion-sort_recur(a, n-1);//how does this line work acts like a for loop. It keeps going until it reaches the second element. Then it returns to the third element. Then to the fourth and so on...