mrnutty 761 Senior Poster

>>fromBinaryToDecimal

To convert from binary to decimal you use the expansion rule.

For example : convert "1010" to its decimal value.

To convert 1010 into a decimal value, we note the position of each bit.

3 2 1 0 //position of each bit
1 0 1 0  //binary number

Now we use the general expansion rule:
To convert from binary to decimal the general rule is: a0 * 2^x + a1* 2^(x-1) ...
ax * 2^0, there "^" represent the power function, and x represent the bits position, and ax is the bits coefficient at its position.

So to convert 1010 to decimal we do:

1*2^3 + 0*2^2 + 1*2^1 + 0*2^0

1*8 + 0*4 + 1*2 + 0*1

8 + 0 + 2 + 0 = 10

Thus the binary number 1010 in decimal base is 10.

Now turn that math into C++ code.

mrnutty 761 Senior Poster

I can have this done for you in a hour or so, but its gonna cost you $100.00 dollars, or $130.00 express.

mrnutty 761 Senior Poster

Well thats what a for loop is for. Or you can use strings

string sent = "ILoveYouMary";
string sub = sent.substr(5); //"YouMary"
mrnutty 761 Senior Poster

Well thats what a for loop is for. Or you can use strings

string sent = "ILoveYouMary";
string sub = sent.substr(5); //"YouMary"
mrnutty 761 Senior Poster

>>What if I want the output to be ANY float

rand() has a limit on the highest number it can return, specifically RAND_MAX. So if
you want to output any float number you need to adjust accordingly( or use a better RNG).

mrnutty 761 Senior Poster

You should call it like so:

sort(m,10); //call your sort method
//print the results:

for(int row = 0; row != 10; ++row){
  cout << "(" << m[0][0] << "," << m[0][1] << ")" << endl;
}
mrnutty 761 Senior Poster

Ok, I guess the easiest way to do this is to make your own data structure and insert it into a vector and sort it, then copy it back. So first create a struct to hold the elements.

struct Elem{
	int row;
	int col;
	Elem(int r, int c): row(r), col(c){}	
};

then create a compare function for the Elem struct:

bool elemComp(const Elem& lhs, const Elem& rhs){
	if(lhs.row < rhs.row) return true;
	else if(lhs.row > rhs.row) return false;
	//else both row are equal
	//so compare the column
	else if(lhs.col < rhs.col) return true;
	else return false;
}

now this will be your sort function:

void sortIt(int Array[][2], const int rowSize){
 //...
}

Now inside you are going to create a vector of elems like so :

std::vector< Elem > vecArray;

Now copy the array passed in, into the vecArray like so:

for(int i = 0; i < rowSize; ++i){
	vecArray.push_back( Elem(Array[i][0],Array[i][1]) );
}

Now all you got to do is call the std::sort function on it like so:

std::sort(vecArray.begin(),vecArray.end(),elemComp);

Now the vecArray is sorted the way you wanted it to be sorted. All thats left
is to copy it back into the original array like so :

for(int i = 0; i < rowSize; ++i){
	Array[i][0] = vecArray[i].row;
	Array[i][1] = vecArray[i].col;
}

So now the passed in Array is sorted by its x-axis, and secondary to its y-axis.

mrnutty 761 Senior Poster

Can you the library sort method?

mrnutty 761 Senior Poster

wait are you supposed to sort the rows first, and if there is any collision, like
2 values are the same in the rows, then you use the columns to resolve the conflict if
possible?

mrnutty 761 Senior Poster

Put it into a vector, then randon shiffle it, and get the first element. Here is an
example:

int doIt(){
 declare std::vector<int> variable;
 while input.isgood, put input into variable.
 call std::random_shuffle with variable;
 print variable[0], a random number from the list of inputs given.
}
mrnutty 761 Senior Poster

>>but it's not a reflection of their intellect, it's a reflection of their work ethic

True, but from experience, it seems that low intelligence follow bad work ethics, usually. Maybe the lack of ethics is the result from them not going through puberty yet.

mrnutty 761 Senior Poster

firstPerson Could be that the intelligent people left because they were sick of arrogant rants from judgemental dimwits who cast aspersions on their intelligence. Bye bye

Guilty Conscience ? Take it as it is. This thread was not out for you particularly, so don't flatter yourself.

mrnutty 761 Senior Poster

Instead of making things global, why not make your function take in a _aline as a parameter?
For example ReadConfig(const _aline* line){ /* work with line variable */ }

And all you have to do is make sure that you can call ReadConfig from your file.

StuXYZ commented: I forgot that! +3
mrnutty 761 Senior Poster

Just use strings.

std::string input;
std::string pass = "file.txt";
cin >> input;
if(input == pass){ /* success */ }
else { /* fail */ }
mrnutty 761 Senior Poster

Yea I guess you can post it now. Here is what I was talking about:

#include <iostream>

using namespace std;

class Foo{
	Foo *ptr;
	int n;
public:
	Foo(): n(), ptr(this){};
	
	void print()const
	{	cout << n << endl;	}

	void change()const
	{	ptr->n = 10;	}

};

int main(){

	Foo f;

	f.print();
	f.change();
	f.print();
}
mrnutty 761 Senior Poster

Think about it first. If you have a string like so :
string sentence = "This is a sentence that needs to be splitted";
how would you go ahead and get word by word? How would you start? Use this as an exercise.

mrnutty 761 Senior Poster
Lusiphur commented: Thanks for the reference link :) +1
mrnutty 761 Senior Poster

I say no, you need to assign variables in a class in the constructor of the class. PROVE IT!!

I will gladly show you a way. But I want others to take a crack at it to. The solution
I show you will tell you that const-correctness is a guideline, not a strict restriction.

mrnutty 761 Senior Poster

So, if there will be no add or remove of books, I suggest to use an array that you can allocate automatically, like this:

string myArray[300];

So, the construction of the array will be done at compile-time and there will be no construction cost at run-time.

If you're using std::vector, consider resizing the vector at the beginning to avoid memory reallocation costs when resizing is needed.

Using raw arrays is hardly ever the correct solution. Even if there is no need for the
extra operation, using vectors is always better than using raw arrays, especially at
such an early stage. And worrying about pre-mature optimization, is the root of all evil.

mrnutty 761 Senior Poster

Say you have a class Foo, and it contains some member variables. And in that class
you have a const-correct function. Can you code some way in C++, that changes the private
member variable, inside the const-correct function. For example :

class Foo{
 int num;
public:
 void doIt()const{
      num = 5; // compile error
  }
}

In other words, can you somehow change num, inside the doIt() function?

Hint, it is possible.

mrnutty 761 Senior Poster

The right way depends on the situation. But I would suggest to do something like this:

#include <vector>

struct Book{
 string _name;
 string _author;
 float  _price;
 //...more info
 Book(const string& name,const string& author, float price)
   : _name(name), _author(author), _price(price){}
};

int main(){
 std::vector<Book> listOfBooks;
 listOfBooks.push_back( Book("America","Obama Hussian", 59.95);
 //add more books
 func1(listOfBooks); //do stuff
 func2(listOfBooks); //do more stuff
 //and so on...
}
mrnutty 761 Senior Poster

Okay, sorry I'm feeling like I'm getting mixed answers now:

Wisaacs:


FirstPerson


So you CAN or CANNOT subtract a string from a string?

@FirstPerson
How does that calculation end up equaling {c,d}?
It seems like you would end up with {b,c}, or {} nothing.

Opps, your right, the result would be {b,c}.

You cannot subtract strings because it doesen't make sense. But I'm just telling
you that you can subtract sets, which strings could represent, and by defining the appropriate operator.

mrnutty 761 Senior Poster

I wrote this DateClass some time ago, see if you find a use for it. Study carefully and
you might find what you wanted.

#pragma once

#ifndef DATE_TIME_H_
#define DATE_TIME_H_

#include <ctime>
#include <string>
#include "CommonFunction.h"

using std::string;

typedef unsigned long ulong;

struct DateInfo{			
	ulong seconds;//current seconds
	ulong minutes;//current minutes
	ulong hours;//current hours
	
	ulong year; //current year
	ulong dayOfMonth; //current day of month [1-31]
	ulong dayOfYear; //current day of year since januaray 1st [0-365]
	ulong monthOfYear; //current month of the year [ 0 - 11 ]

	string day; //current day [mon-sun]
	string month; //current month [jan-dec ]
	

	string meridiem()const{ return (_amFlag? "AM" : "PM" ); }	

	DateInfo(bool isAm = false) : month(), day(), year(), hours(), minutes(), seconds(), _amFlag(isAm) {
	}
private: 
	bool _amFlag;
};

class DateTime{
public:
	typedef time_t TimeType;	
	typedef tm TimeInfo;
private:
	DateInfo dateInfo;	
public:
	DateTime(){ _initDate(); }
	const DateInfo& info(){ 
		return dateInfo; 
	}	
private:
	//helpers
	void _initDate(){
		TimeType rawTime = TimeType();
		TimeInfo info = TimeInfo();
		time( &rawTime );
		info = *(localtime(&rawTime) );		
		
		dateInfo = DateInfo(info.tm_hour < 12 ); //check if its am or pm

		dateInfo.seconds = info.tm_sec;
		dateInfo.minutes = info.tm_min;
		dateInfo.hours = _converToRegularTime( info.tm_hour );

		dateInfo.dayOfMonth = info.tm_mday;
		dateInfo.dayOfYear = info.tm_yday;
		dateInfo.monthOfYear = info.tm_mon + 1; //offset so jan = 1, feb = 2 ...

		dateInfo.year = _startYear() + info.tm_year;	

		dateInfo.day = _convertToDay( info.tm_wday );
		dateInfo.month = _convertToMonth( info.tm_mon );
	}
	const int _startYear()const{
		return 1900;
	}
	string _convertToDay(int dayNum)const{
		string day = "INVALID";
		switch( dayNum ){
			case 0 : day =  "SUNDAY"; break;				
			case …
mrnutty 761 Senior Poster

You should be fine, but you can always separate your logic :

if(condition1 && condition2){
  /*logic here */
}
if(condition1){
  if(condition2){
     /* logic here */
  }
}

But,you don't even need isOccupied variable, if you default initialize player to
null, in the class, then you can just check if seat[x].player == NULL.

But I see you are using raw arrays, just use vectors instead.

Also, maybe some context would help so we can help better the design. For example,
I question why inRound and requireAction as a member variable. Those name suggest
to me that, thats the responsibility of some other class. Remember to minimize
the things the classes needs to do, if possible.

mrnutty 761 Senior Poster

ha, yeah that's pretty stupid. How can you subtract "Cow" from "Toyota Hybrid"?
I get it now, the iterators can work mathematically because the containers they refer to can be used as mathematical values....right? Closer?

You can, depending on the context. For example, in set theory you can subtract sets.
Let A = {a,b,c,d} and B = {a,d,x,y}, then A - B = {c,d}.

mrnutty 761 Senior Poster

and another one :

#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
#include <iterator>

using namespace std;

int main(){
 string num;
 cin >> num;
 //print each digit
 std::copy( num.begin(), num.end(), std::ostream_iterator<char>(cout," "));
 //get sum
 int sum = std::accumulate(num.begin(),num.end(),0) - '0' * num.size();

 cout << "sum is = " << sum << endl;

 return 0;
}

Yes I know, no error checking. Thats because the user knows better, than to mess with me or my program.

mrnutty 761 Senior Poster

Thank you, I actually figured that out about a minute after posting that hehe... but another question along those same lines if thats okay.

How can I use an if statement to decide whether the input is a character or an integer?

if(x == char)
//code here...
if(x == int)
//code here...

I know that code is totally wrong, but it gets the point across. Anyone know how to make that happen?

First, why would you want to do that? Second you cant do that in C++, because no
matter what, you need to define the variable's type before getting an input from the user.

mrnutty 761 Senior Poster

Why are you guys using void*, ewww on that. This is C++, use its power.

mrnutty 761 Senior Poster

No I want take one letter and convert that to integer. If that is not possible I have to use array or vector and size would be big.

char n1 = '1';
int num = n1 - '0'; //num equals 1
mrnutty 761 Senior Poster

Look here for a complete description of the problem. Your code should follow the coding standards,
good names, spacing, easy on the eyes...etc. Make sure you handle all test case and
boundaries. Good Luck, and happy coding. Although this is a C++ forum, it would be nice to
see some different language used to solve this, but not necessary though.

mrnutty 761 Senior Poster

Yes, I charge by the hour. The rate depends on the project. Can you supply more info.

mrnutty 761 Senior Poster

Can you show more code. It looks fine to me.

mrnutty 761 Senior Poster

So you want to convert it into an int array?

mrnutty 761 Senior Poster

Ok, since its been a couple of days since this thread started, i'll post my solution.
Its not very strict but gets the job done enough.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

typedef std::vector<int> IntVector;
typedef std::vector<IntVector> TriangleType;

long bottomUpSumTriangle(const TriangleType& tri){
	TriangleType triangle(tri);
	for(int row = triangle.size() - 2; row >= 0 ; --row){
		for(int col = 0; col < triangle[row].size(); ++col){
			int leftChild =  triangle[row+1][col];
			int rightChild = triangle[row+1][col+1];
			triangle[row][col] += std::max(leftChild,rightChild);
		}
	}
	return triangle[0][0];
}
IntVector toIntVec(const std::string& str){
	stringstream ss(str);
	IntVector column;
	int val = 0;
	while(ss >> val){			
		column.push_back( val );
	}
	return column;
}
int main(){
	ifstream fileIn = ifstream("triangle.txt");
	if(!fileIn){ return -1; }
	TriangleType triangle;	
	string str;
	while(getline(fileIn,str)){
		triangle.push_back( toIntVec(str) );
	}

	unsigned long ans = 0;

	if(triangle.empty()) 
		ans = 0;
	else if(triangle.size() == 1) 
		ans =  triangle[0][0];

	ans = bottomUpSumTriangle(triangle);

	cout << "Max sum = " << ans << endl;
	
}
mrnutty 761 Senior Poster

A int is not going to hold a number that big. Use __int64 instead.

__int64 n = atoi("11111111111111");
mrnutty 761 Senior Poster

You need to pass it an iterator!!!!!!!! Even you said it.

But when you use the operator[], on a vector you are de-referencing it! Which means
you access the elements stored, in your case its a string. So basically, now you
are left with trying to turn a string into a vector iterator, which is not possible.

mrnutty 761 Senior Poster

>>fstream FILE

Change the name from FILE to something else like file, because you have a name clash
with the standard FILE defined in cstdlib header file.

mrnutty 761 Senior Poster

I think you are looking for random number generator. Here is an example :

#include <iostream>
#include <ctime>

int main(){
 srand(time(0)); //seed random number generator

 for(int i = 0; i < 5; i++){
    for(int j = 0; j < 5; ++j){
        int randomNumber = rand(); //use rand() function to return a random number
        cout << randomNumber << " ";
     }
    cout << endl;
 }

 return 0;
}
mrnutty 761 Senior Poster

Lol, I was wondering where you went Vernon, was starting to miss your post lol.

>>This is driving me mad! Explanation please

Here is a small hint, start from bottom-up, instead of top-down.

mrnutty 761 Senior Poster

>>Strings used to be an array of char in C-style coding. Now they're objects in C++.
Forget about what it used to be is C. std::string is a class. An instance of a class
is called an object, so std::string name , here name is an object, because
it is an instance of a class.

>>Does this mean that int and char are not objects?
As pointed out, int and char are primitive data types. The are P.O.D

mrnutty 761 Senior Poster

The best thing to use is std::map here. That will give you very good performance.

Here is an example :

#include <iostream>
#include <map>
#include <string>

using namespace std;

typedef pair<string,int> NamePair;

int main(){
	std::map<string,int> listOfNames;

	listOfNames.insert( NamePair("jeff",0) );
	listOfNames.insert( NamePair("Don",1) );
	listOfNames.insert( NamePair("Calvin",2) );

	//or read from a file with names and insert it into the map

	string input;
	cin >> input;

	if(listOfNames.find(input) != listOfNames.end()){
		cout << "Found in list\n";
	}
	else cout << input << " is not in my list\n";
}

You could read from a file that contains names, and insert it into the listOfNames,
then use that for guidance. Here is some reference
for std::map.

mrnutty 761 Senior Poster

Make a simple timer class to simplify stuff. For example :

#include <iostream>
#include <ctime>

using namespace std;

class ClockTimer{
public:
	typedef time_t TimeType;
private:
 TimeType startTime;
public:
 ClockTimer(): startTime(clock()){
 }
 TimeType elapsed(){
    return clock() - startTime;
 }
 TimeType elapsedInSec(){
   return  TimeType(elapsed()/float(CLOCKS_PER_SEC));
 }
 void start(){
    startTime = clock();
 }
 void reset(){
    startTime = clock();
 }
};

void wait(unsigned long sec){
	ClockTimer timer;
	timer.start();
	while(timer.elapsedInSec() < sec) continue;	
}
int main(){
	cout << "Loading...\n";
	wait(5); //seconds
	cout << "Done\n";
	
	ClockTimer timer;
	timer.start();
	while(true){
		if(timer.elapsedInSec() > 1 ){			
			cout << "moving character\n";
			timer.reset();
		}
	}
}
mrnutty 761 Senior Poster

What part of C++ troubles you, my young lad?

mrnutty 761 Senior Poster

Yes the answer is 7273, and posting solutions are welcome.

mrnutty 761 Senior Poster

Although you created no object, the point is that, the compiler might create
a static instance of the base destructor, thats why there might be a linking error.
Whether the compiler does this or not, is depended on the compiler, but recent compiler
will not do this, but older ones might.

mrnutty 761 Senior Poster

Sorry thats not the correct answer.

mrnutty 761 Senior Poster

when getting a name, into a string variable, or any input from into a string variable
if you use getline(cin,someStringVariable) , then it reads the whole line
into the someStringVariable. The problem with yours was that cin stops reading when
it reaches a whitespace. because of that, there could be some input left in the buffer,
and in your case it was, which causes the input to fail. So when getting a name into
a string a variable use getline(cin,name).

mrnutty 761 Senior Poster

You should only have 1 main, 1 entry point! I don't know if you have 2 int main() , but if you do, then delete one of them or transfer on of them to the other.

usafsatwide commented: Thanks for all your help +1
mrnutty 761 Senior Poster

Post full error

mrnutty 761 Senior Poster

Ahh, you define the variable "info" twice, one in line 13 and the other in line
28. Just delete line 13.