tetron 22 Junior Poster

Hi i have only skimmed your code but there are a couple of things that stand out as potential problems

1: in remove number:
with the first for loop you want the original size not size -1, otherwise, if you try to remove the last number in array it won't be found.

void removeNumber(int *& array,int number, int &size)
{
        IntArrayPtr temp;
        size = size-1;
        temp = new int[size];
        for(int i=0;i<size;i++)
        {
                if(array[i] == number)
                {
                        for(int j=i;j<size;j++)
                        {
                                array[j] = array[j+1];
                        }
                }
        }

so you need to add a variable say istop that has the old size to use with the loop before you save the new size

The other issue won't be so obvious and may not matter for you usage, again addNumber has a size being used twice where different values are wanted. and output should leave array unaltered.

tetron 22 Junior Poster

I'm not sure what the problem is going to be explicitly, but you might want to try adding paint() on activate aswell as on paint itself.

I remember having an issue with when the window was drawing with VIsta but went away when I used a different approach. You could place paint calls explicitly in your frame handler rather than just to listen for WMPAINT

I have a problem with this Window Procedure. in new versions of Windows OS, when I run the program, at first everything is painted & then paintings disappear
there's also a problem with mouse click messages. I think they are not caught properly by window procedure.
there's no problem in Windows XP. These problems are in Vista & Seven.
I can attach all the project if necessary!

tetron 22 Junior Poster

is posible expalin my for what use %s in a code line

cmdLine.Format("\"%s\" \"%s\" %d %s %s %s", playerFile, moviePath, 10,
cameraName, selectDate, movieID);

i need now how works this code line

It is used as a placeholder to substitute values into the place of:

so the first %s is the first variable whaich as walt says is treated as a string so say the values were as follows

playerFile  = "str1";
moviePath = "str2";
cameraName = "str3";
selectDate = "str4";
movieId  = "str5"

the the output into CmdLine is something like "str1" "str2" 10.00 str3 str4 str5 the ten is being treated as a double via %d

tetron 22 Junior Poster

It is windows games programming books and articles that probably have the cleanest explanations of what you want to know.

There are ways to short cut building a window, depending on the version of visual studio you use. but it is worth knowing how to construct a window without any class wizard.

Once you have built the window the rest of the interface is fairly intuitive. A generic system like ancient dragon mentions maybe best in the long term. But for now, when you look for books on game programming they give you the information for using the windows api's and will give the code for constructing a window.

The code for building the window will stay almost the same for your windows applications.

The code gets messy when you see it without explanation and just to build a window that does nothing other than show takes code that looks a bit like this:

#include <windows.h>
BOOL Initialize(int iCmdShow)
{
  WNDCLASSEX    wndclass;

  // Create the window class for the main window
  wndclass.cbSize         = sizeof(wndclass);
  wndclass.style          = CS_HREDRAW | CS_VREDRAW;
  wndclass.lpfnWndProc    = WndProc;
  wndclass.cbClsExtra     = 0;
  wndclass.cbWndExtra     = 0;
  wndclass.hInstance      = m_hInstance;
  wndclass.hIcon          = LoadIcon(m_hInstance,
    MAKEINTRESOURCE(GetIcon()));
  wndclass.hIconSm        = LoadIcon(m_hInstance,
    MAKEINTRESOURCE(GetSmallIcon()));
  wndclass.hCursor        = LoadCursor(NULL, IDC_ARROW);
  wndclass.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
  wndclass.lpszMenuName   = NULL;
  wndclass.lpszClassName  = m_szWindowClass;

  // Register the window class
  if (!RegisterClassEx(&wndclass))
    return FALSE;

  // Calculate the window size and position based upon the game size
  int iWindowWidth = (m_iWidth * 1.5) + GetSystemMetrics(SM_CXFIXEDFRAME) * 2, …
tetron 22 Junior Poster

As salem stated you are asking for an input of a char which is a sinlge digit or letter.

so this can only give one letter at a time however, you are also using a while loop so you are
getting first

char digit;
int count(0);
while(cu != -1)
{
//this line might make it clearer
cout << "call number: "<< count << std::endl;
cin>> digit;
cout << "is digit: " << digit << endl;
}

this while loop runs four times
if you use std::string you will need to change your stop condition
but it will take in a whole word at a time.

so to read in one word

#include <string>
#include <iostream>
using namespace std;

int main()
{
string multiple_digits;
cout << "enter a number" <<endl;
cin >> multiple_digits;
cout << "Is digit:" << multiple_digits << endl;
return 0;
}

To check that this is a number will require a function
say:

bool check_only_numbers(std::string &str)
{
bool ret(true);
   int sz = (int) str.size();
  for(int i = 0; i < sz; ++i)
 {
    if(str[i] < '0' || str[i]  > '9')
    {
       ret = false;
       break;
    }
 }
return ret;
}

there are cleaner ways to write this last function

thank you for your help, but do you know why will it happen in this way. why the print out result is not Is a digit!a123 ?

tetron 22 Junior Poster

you are very close to getting ti working the problem is how you are converting an int to char assuming that you are only going from 0 to 9 you can have

//this is either the relative or absolute file path
std::string base_file = "data";
std::string after_number = ".txt"
for(int fid(0); fid < 10; ++fid)
{
 char digit = '0'  + fid;
 std::string cur_filename = base_file + digit + after_number;
 std::ifstream fin(cur_filename.c_str());
 if(fin.is_open() == true)
 {
    //etc..
    fin.close();
 }
 else
 {
     std::cout << "could not open file:" << cur_filename << std::endl;
  }
 
}

the digit code will need expanding for larger number of files but it is just a file manipulation check what the string looks like before opening.

For example if I have this int type variable X that increment from 1 at the beginning to 10 when the program ends, how to open and write to 10 different files (data1.txt,data2.txt,data3.txt....) everytime X increments?

I've tried with the following but it didn't work:

string filename ("data");
int X;
ofstream out;
char number;
for(X=1;X<11;X++)
{
number=X;
filename+=number;
out.open(filename.c_str());
....
...writing....

out.close();
}
tetron 22 Junior Poster

I'm confused as to where im supposed to put the the location of the file such as C:\\Documents and Settings\\user\\Desktop\\myfile ??

you will need a file extension too.

the double \\ are needed for the direct string input but if you

std::string location = "C:\\folder1\\folder2\\my_file.txt";
std::cout << location << std::endl;
//your output will be :
//C:\folder1\folder2\my_file.txt
std::fstream(location.c_str());
tetron 22 Junior Poster

im calling this function from main

bin_p.binary_print(outs, n);
^that is in int main()

void binary_print(ostream& outs, unsigned int n);
^this is in the header file

void rec_fun::binary_print(ostream& outs, unsigned int n)
	{
		if(n < 2)
		{
			cout << n << endl;
		}
		else if(n >= 2)
		{
			binary_print(outs, n/2);
			cout << (n%2);
		}
	}

^implementation file

all 3 files have #include<iostream>,<cstdlib>,using namespace std

hope thats enough info for u to help me!! please :)

What the error is telling you is that it doesn't know what outs is.

Before you call bin_p.binary_print(outs, n); you must have declared outs:
something along these lines: ostream outs; this is the most likely place where you have made an error perhaps a typo in variable name.

Another question:

your method does not use the variable <icode>outs</icode> so what is its purpose?


Occasionally you can have problems using references of fstreams but I don't think that this is an issue here.

tetron 22 Junior Poster

caveat: This code is doing lots of things that look messy. Especially for the error that you are unfamiliar.

Your error means that you need the .h file or at the top with somting like

int GenerateRandomValue(int v1, int v2);

You will also need the definition of the function at someplace too.

Your error basically means that you are using a function that has not been defined. Becuase it is a compiler error rather than
a linker error this means that the computer does not know the signature of the function.


it i get a error when i try to compile ''C3861: 'GenerateRandomValue': identifier not found''
i cant seem to figure this one out

help
im more of a vb.net guy

tetron 22 Junior Poster

Your first check should n't happen as you always want to prompt for
password so
set should look more like this

and maybe should have a different function name
as you care actually checking password rather than setting s1

void Password::set()
{

cout<<"Enter password"<<endl;
getline(cin,pass);


if (pass != s1)
{
	cout<<owner<<endl;
	cout<<"Enter password again"<<endl;
	getline(cin,pass);
}
if (pass !=  s1)
{
	cout<<owner<<endl;
	cout<<"Enter password again"<<endl;
	getline(cin,pass);
}
if (pass  != s1)
{
	cout<<owner<<endl;
	cout<<"Good bye"<<endl;
 }
 if (pass == s1)
 {
	cout<<owner<<endl;
	cout<<"Welcome"<<endl;
 }
}
tetron 22 Junior Poster

Ok, I am a little confused I assumed that you were having a problem with the read.

Now several of your methods, are using approaches different to what I would choose to do.

When you say an error do you mean that the code crashes or just doesn't return the value you were expecting.

You might have a problem with !fbin.eof() this can lead to issues but I can't remember precisely why.

It is possible that your for loop is going beyond the end of your file.
You would probably be best off stripping out the open of binary files and stick to ascii as it is easier to maintain, until the code is working.

To find the records - get the size of the file and divide by RecSize would be one option


I am assuming that you are not calling option change_path
does your file_name not have an extension ie ".txt"

for test purposes add the following:

int get_used_records() {
  char temp[20];
  int counter = 0;
  for (int i = 0; !fbin.eof(); i++) 
  {
      std::cout << "i == " << i << " " << counter << std::endl;
      fbin.seekg(recSize * i);
      fbin.read(temp, sizeof(name));
      if (strlen(temp) != 0)
      {
               std::cout << "temp = " << temp << std::endl;
	counter++;	
      }
return counter;
}

and set task to 4

Line 37: sizeof(task_list) / 4 doesn't look pretty

The other question is what exactly is your input …

tetron 22 Junior Poster

I tried to add ios::beg to the function, but it gave no result. I actually though that the seekg and seekp functions set the absolute position in the file stream, but maybe I'm wrong.

They should do but there was a small chance of an overflow error.

I'm not sure what is happening - I assume that you are checking that n is meaningful.

it might be worth checking the return for all the methods
ie.
http://http://www.cplusplus.com/reference/iostream/istream/read/

and that the file is_open();

tetron 22 Junior Poster

you have not got {} matched in all places.

The compiler won't give you a line number for this so if your code isn't too long and you still can't find the error post it.

I will show the code if you want to see the error.... Am still working through this program but with this error i am not getting anywhere..

stricklypni commented: THANK YOU I KNOW C++ DONT TAKE THE SMALLEST SYNTAX ERRORS +0
tetron 22 Junior Poster

It might be an idea to use ifstream and ostream and open and close the file as needed.

I have looked at your code and haven't spotted the mistake. seekg(pos) should be setting an offset. However, I'm not sure whether the reason that you are having to move to the begining of the file first might be because the file is still open for writing.

What I suggested before is make line 92:

fbin.seekg(recSize * n, ios::beg);

without line 91
this says to use an offset from the explicit position start

the seekg() returns a value that might be showing an error.

tetron 22 Junior Poster

If you have a sufficient version of microsoft visual studio
you might be able to use the CImage class

http://msdn.microsoft.com/en-us/library/d06f3fhw(VS.80).aspx

however, express doesn't have this.

Otherwise it is a messy procedure as there is more than one jpeg encoding you probably will need to read up on bitmap headers or find someone's sample code.

tetron 22 Junior Poster

a couple of things to note == can be used directly

so

if(s1 == pass)
{
}

more importantly
you are using

else if(pass != s1)
{
}

which only only happens (i.e. is checked), if none of the earlier conditions fire

so you meant:

if (pass.compare(s1) != 0)
{
	cout<<owner<<endl;
	cout<<"Enter password again"<<endl;
	getline(cin,pass);
}

if (pass.compare(s1) != 0)
{
	cout<<owner<<endl;
	cout<<"Enter password again"<<endl;
	getline(cin,pass);
}

if (pass.compare(s1) != 0)
{
	cout<<owner<<endl;
	cout<<"Good bye"<<endl;
	cout << "exit" << endl;
}

if (pass.compare(s1) == 0)
{
	cout<<owner<<endl;
	cout<<"Welcome"<<endl;
}

you might want to think about adding a private method

std::string get_password();

and putting this in a while loop to count the max number of tries
with break

tetron 22 Junior Poster

Without seeing a full example, it seems odd behaviour.

As a first thought, I assume that you are talking about opening a file that is acting as a database and you want to move to the first entry.

you might try explicitly adding the ios::beg

fbin.seekg(0, std::ios::beg);

if this doesn't achieve anything we will need more information as to file format and where you opened the file.

P.S. it is helpful to use code tags

Why do I have do use the Seekg()-function two times in a row to make it work?

Code:

fbin.seekg(0); //jump to record at start of file
	fbin.seekg(0); //jump to record a second time (else it won't work)
	fbin.read(name, sizeof(name)); //read from data field 1
	fbin.read(reinterpret_cast<char*>(&age), sizeof(int)); //read from data field 2

	cout << "Name: " << name << endl;
	cout << "Age: " << age;
tetron 22 Junior Poster

Ok I will give this a try. One question currently though. what is v_pos ?

What I was giving as an alternative design had v_pos as a std::vector<int> the idea is that the last item is the last move tried.
so pos is just an index, on reflection this might have been better wrapped in side a coord class in the first place.

Now it is not necessary to change your entire design over at this point as it should work for small boards.

If you use the functions to remove the magic numbers then you can alter the , width & height of your board. This might indicate if my worries about your code taking too long to run will be addressed.

I would first check that al the solutions are being found with 4x4 and 8 knights and 5 x 5 with 13 knights

and then try increasing the size gradually.

I have not tested this to see if there is an issue but my concern is that, in effect, you are trying to think 31 moves ahead and even with 2 or three options a turn this is getting close to being too big to solve iteratively.

I know in a game a PC can take 45 minutes for 10 move depth with a heuristic algorithm for some games.

If I was doing this without iteration I would make the algorithm learn the shapes of placing the knights, In …

tetron 22 Junior Poster

without seeing your exact code there is some guess work involved.

If you put your call to new int a try catch block you might get a clearer answer as to where the error is coming.

DirectX is already a class that is known somewhere to visual studio and although I think you probably don't have a conflict it is possible that you are not using the class that you have defined.

Is there a reason why you have your own class called DIRECTX ?

If not try renaming it and the variable DirectX . I am not familiar enough with microsoft directX to know if you have a potential naming conflict but it is something to consider. This is something to be careful of with all your variable names.

Your DIRECTX constructor uses a this pointer, which could cause confusion, why not just have

counter = 0;

etc.

The other things that could be happening.

- cout - may not be writing from the call to DirectX
- Does your directX inherit - if so it is calling the base constructor and this might require that your window is valid.

If you try commenting out everything other than the first cout what happens?

DIRECTX* DirectX = 0;

Its defined like that.


Its succeeds.

But I know where the error is, I just don't know WHY it is there. I mean,

DirectX = new DIRECTX(MainWnd);

Should call the …

tetron 22 Junior Poster

A final thought for things that can go awry is when your initialisation is using global variables.

I have had Visual Studio 2003 fail to build global variables in the order that it was told. If you are doing auto registering classes or the like this can cause unexpected behaviour.

It might be worth explicitly checking any globals you use in initialisation are correct.

Also the other thing I have found is - it is often worth rebuilding a solution from scratch. So that all of the inclusions etc have to be redone. With Visio I have sometimes had the system misbehave to the point where you have to start again rather than trying to find the phantom error.

This odd behaviour has sometimes been contributed to by my antivirus.

Edit: I call the thread creation before the window creation and it works now. Very very strange...

tetron 22 Junior Poster

minor issue in you check position in that are you checking the current position is empty as well as not attacked?

There are some maintenance issues creeping-in and these are being exagerated by changing design half way throuh

you might want some methods or classes that hide some of the magic numbers

int get_ind(int row, int col)
{
 int ret(-1);
 if(row >= 0 && row < width)
 {
   int ret = row + col *width;
   if(ret >= size)
   {  
       ret = -1;
   }
 }
 return ret;
}
bool is_knight(bool * board, int row, int col)
{
 bool ret(false);
 int ind = get_ind(row, col);
 if(ind != -1)
 { 
    ret = board[ind];
  }
 return ret;
}
bool am_I_attacked(int row, int col)
{
  bool ret(false);
  int ind = get_ind(row, col);
  if(ind != -1)
  {
     if(is_knight(row + 1, col + 2))
     {
        ret = true;
     }
//etc
   }
}

this makes it easier to see rather than the -17 and col >2

although I think from number of steps you might need to completely change board int board[width * height];

void add_knight(int * board, int row, int col)
{
//just set inds greater than current pos
 set_board(board, row + 1, col + 2);
 set_board(board, row - 1, col + 2);
set_board(board, row - 2, col + 1);
set_board(board, row + 2, col + 1);
++knightTracker;
 }

void set_board(int * board, int row, int col, bool b /*=true*/)
{ 
 int ind = get_ind(row, col);
 if(ind != -1) …
tetron 22 Junior Poster

Line 156

result = result *=i;

too many =

result *= i;

although I'm not sure that this would not run ok as it was.

There is nothing obviously wrong, although your choice of variable names may conflict with cmath what happens when you run them at the moment:

say;
log 1000 = ?
and
factorial 5 = ?

tetron 22 Junior Poster

Edit: also for anyone confused.

That would include me - your questions bounce around alot for a single thread:)

This is the function I was talking about:

char* ssprintf( char* szString, ... )
{
	char* szBuffer = ( char* )malloc( 1024 );
	
	va_list va_alist;
	va_start( va_alist, szString );
	vsprint f( szBuffer, szString, va_alist);
	va_end ( va_alist );
	
	return szBuffer;
}

There is nothing to clean up at this point although you should not use malloc but new As the function has a return the returned char * now has responsibility

Engine.Win.m_hCalcThread	= CreateThread( 0, 0, ( LPTHREAD_START_ROUTINE )CalcThread,  0, 0, 0);

Worked yesterday, but now I converted my code to a win32 project and run a dialogbox instead of a main window.
Now the thread never gets created. It gives off no error

does it return a valid HANDLE ?

try writing to an edit or message box rather than to console.
There are a lot of changes going to a win32 project

tetron 22 Junior Poster

start quote:

# include <stdio.h>

abc (y++); // error here

end quote.

This result surprised me too. I guess it is because

y++

passes the variable into the function as y
and then tries to further alter the variable after entering the function which adds potential undefined behaviour so the compiler assumes a mistake.

as you could alter the value of y in the function.

you could have

abc(++y);

because the value of y is set before the function calls it

The comiler can see the different return type for the two operators as can be seen here:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

but I am sure someone could give you a clearer explanation

tetron 22 Junior Poster

Main needs to cin

std::cout << "please  enter operator" << std::endl;
std::cin >> character;

before

switch (character)
{
case '+' : addition();
tetron 22 Junior Poster

KB.cpp(18) : error C2447: missing function header (old-style formal list?)

public:
	Password(void);

I would not expect to see void void being used as a parameter () is standard.

but what I don't see is a definition of

Password::Password() 
{
}

and the compiler might be complaining that it thinks that you have a function without a return type and not seeing a constructor.
though you might well just not have shown us :)

as well as line 18 as banfa says

tetron 22 Junior Poster

My program keeps crashing when not in debugging mode. So now i'm debugging manually, or well, log everything to find where it is crashing

DirectX		= new DIRECTX(); // Creating DirectX

is not calling :

DIRECTX::DIRECTX(HWND Window)

but

DIRECTX::DIRECTX()

so we can't see where the problem is.
There may also be issues in calling your variable & class directX, etc

tetron 22 Junior Poster

Lets see if i have your memory question correct this time:

you have a char * that you want to pass into a function set some values then return the char * Now I see a couple of issues with you question that lead to me being slightly confused.

1 - you can only empty a variable when everything has finished with it
you could assign a "" tp the pointer if new wasn't used but c++ has classes that would make your life easier.

If you say want to manipulate a char * to make an output then you really want to use std::string this is a useful class that is like a char 8 and takes care of some of the handling anyway

#include <string>
#include <iostream>
#include "my_class.h"

int main()
{
char * pc = "hello world"; // a normal cahr *
std::string str; 
str = pc; // a string can take a char * 
//you can also directly output with cout
std::cout << str << std::endl;

//define a second string using the constructor
std::string str2("good bye world");
// a class to hold some functions
my_class c;
c.write(str1),

//turn str 2 into "good bye world hello"
str2 = c.add_hello();
//a function taking a string
c.write_c_string(pc);
c.wrtie_c_string("my name");
//the .c_str() gets the same type as char*
c.write_c_string(str2.c_str());
//can empty str2 with
str2.clear();
//haven't used new so no delete
return 0;
}

now we have three text strings to send to a function to …

tetron 22 Junior Poster

Without seeing your code it is a tricky question to answer.

What you probably want to do is put both programs into
classes then you can
create an instance of the class and decide whether to run it on the if

say a simplified version of your code looked like this

#include <iostream>

int main
{
//program 1 start
int a(1), b(3);
double c= -1.3;
std::cout << "a+ b = " << a + b << " c => " << c << std::endl;
return 0;
}

now a basic class would then become
program1.h

class program1
{
 program1();
 void init(int na, int nb, double nc);
 int run();
int a, b;
double c;
};

program1.cpp

program1::program1()
: a(0), b(0), c(0.0)
{
}
//set all your variables
void program1::init(int na, int nb, double nc)
{
 a = na;
 b = nb;
 c = nc;
}

int program1::run()
{
//program 1 start
std::cout << "a+ b = " << a + b << " c => " << c << std::endl;
return 0;
}

and then you can call in main

#include "program1.h"

int main()
{
 bool use_p1(true);
 program1 pr1;

 if(use_p1 == true)
 {
    pr1.init(1, 3, -1.3);
    int ret = pr1.run();
  }
  else
  {
     /*
       do the same for other program
    */
  }

return 0;
}

classes are usefui and should have a clearer design than this abstraction.

It is possible to call .exe from inside code but it gets messy and …

tetron 22 Junior Poster

Alrighty, one more for the road.
say I make a function that is a char pointer,
in the function I malloc into a char pointer a sizable amount of memory.

new is preferable way of creating memory

this is a design decision once you call new somewhere the memory must be deleted. sometimes one class will create the memory while another will be incharge of deleting it.

//gives control of new block in return
char * my_function()
{
char * p_memblock = new char[big_size];
/*
other stuff
*/
return p_memblock;
}

if your function does somthing like this then the function no longer has responsibility for the pointer
if p_memblock was a member variable you can clean it up with delete[] say in the destructor but if it was a local then

{
 char *pc = my_function();
 /*use pc
 etc..*/
 //now clean up
 //finished with pc so delete
 delete [] pc;
 pc = 0;
}

normally new and delete will be as close together as possible

tetron 22 Junior Poster

Here is a sample header file:

should have:
1- description to ensure that you understand your design
2 - meaningful class name the same as the .h file name
you can have iterator classes in the same header
3 - function names that make sense
4- comments on how to use function on line above
5 - use of public: private: etc
6 - const where necessary

/*
Add description of what your file is doing
in this instance a demo class to show
that inherits all of the functions and member variables from
base foo
*/

#pragma once //MS code guarding to ensure only used once
#include "fee.h" //include the types you use in the function
#include "base_foo.h" //base class

class foo : public  base_foo
{
public:
  foo(); //public constructor so can create instance
  //this comment to be used by intellisense
  void DoSomething();
  //const as it will not change any member variables
  fee get_my_fee() const;
  void set_fee(const fee &cfee){my_fee = cfee;} //no semi colon 
protected:
    //can be used by any inherted class
   virtual void do_nothing();
private:
 fee my_fee //member variable
};//semi colon needed

foo.h has to define any function that your code will want to use

#include "foo.h"
#include <iostream>

//call other constructors using: 
foo::foo()
:my_fee()
{
}

fee foo::get_my_fee() const
{
 return my_fee;
}

void foo::do_nothing()
{
  std::cout << "you can overwrite me with inheritance" << std::endl;
}

//adding one to 'a' in fee
void foo::do_something()
{
 /*further …
tetron 22 Junior Poster

Now some of the terminology you are using is unfamiliar to me.

When you say graph:
are we talking an Excel chart
I.E. lines and points

This would be a traditional graph but my concern is that when i looked up adjacency matrices it uses graphs to refer to "labelled graphs", which appear to have directional flows and if that is the case you might need to be precise in what format is the visual image you expect.

A visual representation of a traditional grpah can be in several forms but basically you are talking about processing an image. A bitmap would be the information that is displayed via the monitor and a .svd would store the information in terms of the lines drawn.

You need to select the input that you want and identify the features that you need.

Your solution would have to be modular:

1 - capture the image
2 - identify the features in the image.
3 - convert the features into a physical description
4 - convert the physical description into desired format ie (adjacency matrix)

Now you should be sure that you can do 2-4 before wasting time implementing 1. this means taking an image in the format that you want to handle with 2 & 3.

The most basic image is the .bmp no compression and you can capture using MFC, etc. But if this is what you are using …

tetron 22 Junior Poster

My comment in my last post was concerned with the following condition.

if (kCheck is false this second condition:

)||(KNIGHTS-knightTracker > spacesLeft)

is unaltered as the number of knights remaining is the same so
unless spaces remaining are reduced this will not fire.

As for finding no solutions...
This is a more complex issue and as I expressed badly before the order of complexity of the problem is such that a brute force recursive function might fail to find one of the two solutions.

If I was doing this recursively, my logic would be every time I add a knight to the board I would add all the squares that are attacked by it. Then every attacked square I would add an attack too reducing the number of spaces left at the same time.

This uses an int for each square rather than a bool so that the move can be unwound easily when removing the last knight placed.

so I would consider the logic of kCheck as it should adjust the spaces left.

The other line that I find confusing without running it is as follows:

findSolutions(boardN, col+1, i,SIZE-(col+rows*WIDTH));

Now this might be corret to give a solution.
What i read this as doing is:
1 - you are stepping horizontally along the row
2 - stepping along each column
3 - reducing the number of spaces left to reflect squares untested by latest run

tetron 22 Junior Poster

You are going to have to avoid some pitfalls with te 32 Knights problem

first is that as a brute force search it will often fail to find a solution

There are only two solutions: as you pointed out.

If you step in a vertical line it will not fail until the 24th piece is down.

This makes it much higher order complexity than the queens problem and you need to check that your code is going to complete rather than run for years.

having said that:

Ok so after a few days, I finally got the 8 queens problem solved. After having so much trouble I decided to practice recursion by doing the same problem but with 32 knights. 8x8 board, place 32 knights without them attacking one another. I am using a 1d array. When calling the program I get a heap corruption error. I am not sure why but recursion is really escaping me. Please help. I can provide other pieces of the code if requested. Thanks

void Board::findSolutions(bool *board, int col, int rows, int spacesLeft)
{
	if(kCheck(board, col, rows)){//Checks the 8 positions around the knight that he can attack
		board[col+rows*WIDTH] = true;// If he can be placed set the position to true
		knightTracker++;

should there be --spaces_left what is happening on the else where the knight is being attacked?

tetron 22 Junior Poster

Ok so after a few days, I finally got the 8 queens problem solved. After having so much trouble I decided to practice recursion by doing the same problem but with 32 knights. 8x8 board, place 32 knights without them attacking one another.

A bit off topic so apologies :)

EDIT this is an extremely wrong comment - you would not believe how good I am at games and missed this, sorry :( Obvious diagonals only solutions.

/*
but a knight in the corner attacks 2 squares.
A knight on the edge 3 - 4 squares 
so it is not possible to place 32 knights without attacking a knight

so i would not recommend a recursive function for this.

You could try a recursive traverse shape function where you paint an area with in lines. If you have a board this is a small step up
*/
tetron 22 Junior Poster

You are using a lot of c code rather than c++ and stl
this makes your code tricky to read.

first an aside it is probably worth moving if(WIN32) to be just a single string definition rather than in the middle of a while loop as it gets tricky to read.

so first you have your big
2-D array

a b c d e f g h 1
....

z x c v b n h j 4

now you can either load in just the values or the values plus the keys

#include  <vector>// dynamic handles the resizing for you

//make the code more readable
typedef std::vector<double> vd;
typedef std::vector<vd> vvd;

class matrix_loader
{
public:
   matrix_loader(int width = 8);   
   bool load_from_file(char * fn);
   std::vector<vvd> get_all_blocks();
   void clear(); //0 every thing
   void set_width(int nw){width = nw;}

private:
   int my_width;
  vvd data; // just values
   std::vector<int> ids; //last column
};

this gives a class where vvd is the desired structure that you want to use

now need to write implementation

#include "matrix_loader.h"
#include <fstream>

matrix_loader::matrix_loader()
:my_width(width)
{
}

void matrix_loader::clear()
{
my_width = 0;
ids.clear();
data.clear();
}

bool  matrix_loader::load(c har *fn)
{
 clear();
//reading in data using stl
 std::ifstream fin(fn, std::ios::in);
 if(fin.is_open() == true)
 {
    //iterate get_line while ..
    int max_count(100000); //overflow protection
    int count(0);
    while(count < max_count)
   {
     vd row;
     for(int j(0) j < my_width; ++j) 
     { 
       double d;
       fin >> d; //read in the double
       row.push_back(d);
     }
     int …
tetron 22 Junior Poster

Touchy aren't you?

...

professionally written libraries always pay close attention to constness.

Wasn't talking libraries I am talking in-house software to create .exe
with 100,000s of lines of code, which I guess from your comments you have rarely worked on.

A library has to work with 3rd party classes so it has to be const to comply with others use and although believing in-house software should be written this way is noble, it doesn't take people into account.

If you design a class

The reason that I keep responding to you is that you are missing the critical issue and detracting from the solution as a result.

This whole problem is about design. If the OP rightly feels that a class needs to have a memory block but doesn't want to declare a temporary like I showed in my first class. Then this is not a set
of const functions in the class.

The declaration of a const function is meaningless in mathematics. It only has meaning in computing so the OP is needlessly worrying that the change won't make sense to the users being mathemaricians.

It is where the const needs to be placed for clarity. As he is copying by values the input to the function, there is limited need for const, but a const might be added to the variables as that does have a mathematical meaning.

- The only question that cannot be answered without knowing …

tetron 22 Junior Poster

an overrated

not an accurate quote!
the use of an adjective somewhat makes a big difference. you limit your answers to the university answers with little regard for the real life situations that occur with programming either large scientific or several professional programming projects.

The const is there to stop amateur slips but when you use a method you should know what its intent is before you use it. you will find many times in life that an accessor is not declared const or an iterator is used and reintroducing const_iterator will take significant time to alter.

If a method might reasonably alter a class but doesn't currently...
Declaring it const and then altering it back can lead to extensive coding changes.

You will notice that a lot of the example code you see doesn't include const because of convenience of typing. But using const is a design decision.

1 - "I have a mathematical class having some numerical functions."
2 - "It is convenient for me"

Both of these statements give a fixed scope of the problem
and although you do get maths class which store local variables that are fixed for an equation they are not designed to persist unaltered so

const my_maths_functions m(0.3, 0.5);

is unusual as any method called that alters the variables should be unambiguous. it is down to the name.

2 - this is a design decision you want so stick to it.

tetron 22 Junior Poster


I wonder did you read the previous posts at all?

Yes. Yet again you are jumping on a single sentence and basing your entire response on that basis.

I have several maths functions and if you are encapsulating them in a class rather than global functions you would get something like:

#include "../my_maths/my_maths_functions.h"

double my_class::my_function(const double x1, const double x2) const
{
 my_maths_functions m;
 //altering m  but not x1 and x2
 double ret = m.myfunc(x1, x2, x3);
 return ret + 2.0;
}

this is a valid const function using myfunc non const

It does not matter that m is altering and you might want more than
one at once in a multi-threaded environment so a global is undesirable for such a generic class

the thing to note is that the class my_maths_functions should not have fixed member variables and it would be contained rather than inherited from by its essence of purpose.

const is used to declare a design purpose and there is no need for your maths_functions to be in a class using func() const;

your variables should be const because you want to leave them unaltered but the function for a maths class does not have this need.

tetron 22 Junior Poster

I have no tried playing around with this

One approach is known as
skinning or a skin
This can change the style of how windows appear used to be popular for windows themes.

Another approach is more re-writing the wheel where you use a window with no frame and redraw the entire window as if it was a graphics image.
--- this gets tricky as you basically recreate every single function such as scroll-bars, minimise

You can even make the windows round but it is a lot of work...
and to use it for applications other than your own?
this is getting close to partially writing your own OS which is best done only in Linux and defeats the purpose.

Hello.

I am quite keen with the win32 api but am tired of the standard windows visual styles (XP/Vista/7) and am wondering how to create my own. Have googled but not found any information, just point me in the right direction.

Thank you very much.

tetron 22 Junior Poster

const is a some what overrated concept that leads to more typing
and maintenance.

In your case myfunc is not const as it alters a member variable
if this is not appropriate to be altered then you need to use a local

double myfunc(double x1,double x2, double x3) const
{
std::vector<double> memory(4, 0.0);
//etc...
}

but your function does not necessarily want this either...
the const is telling the compiler that you are not altering the class
but that is what you are doing and there is no way that the compiler can resolve this problem.

There might be a way to cast the function to const but I don't know it...

the question is why does the other end need to know that your class variable is const....
it should not matter it is only that x1, x2, x3 are not changing that should matter where the function is called! so there is no logical need for the function to be declared const only the inputs!

tetron 22 Junior Poster

!st template class will compile fine until the code is used. TreePath is not defined in the code you have shown

Path has some risky behaviour

T& getLastPathComponent(void) const
{
  return *lastPathComponent;
}

using a pointer that you do not own without any error checking is dangerous
and are you sure you want a reference why not just return the pointer

cout << typeid(*m->getDataNodePath().getLastPathComponent()).name() << endl;

this line is doing too much at once there are many ways in which it could be failing
split it into variables and check each one in turn. there are several points where you could be failing in this line
It should not be in a constructor either

tetron 22 Junior Poster

I will try to be succinct:

1. a static member variable acts like a single common variable
that is a global
so there is only really one 'n' in the whole project

2. a constructor () is called every time the computer has to allocate memory and give an address to a variable

so

//n = 0
CDummy a; //same as CDummy a() first  
//n +=1 
CDummy b[5];// creates 5 cdummies
/*
 so CDummy is called once per slot = 5
n += 5;
*/
CDummy * c = new CDummy(); //an obvious constrcutor
//n += 1

finally the dsstructor is called when the parameter is finished wuth
on delete of a pointer
or end of scope

{//start of scope
//created
CDummy d;
 if(x == 7)
 {
 }
}//end of scope //d is destroyed

so

delete c;
//destructor called once as not delete[]
n -=1
tetron 22 Junior Poster

Hello,

double temp_data = NULL;  //temporary matrix
int u = 654;			// u = the total number of periods in the time series

bk

There are some inconsistancies in your descriptions and implementation.

If this isn't an assignment there are quicker ways to load the data.

1st this line is definitely wrong

double temp_data = NULL;

temp_data is a variable that you are assigning a value
and it like an int can only store one value

what is data nk??

I would try to use vectors:

#include <vector>
#include <iostream>

int main
{
  std::vector<double> row;
  std::vector<std::vector<double>> mat;
 double val (0.0);
  int current(0);
  for(int i = 0; i < 8;  ++i)
  {
   std::cout << "enter val:";
   std::cin >> val;
   row.push_back(val);
  }

  int id;
  std::cout << "enter id:";
  std::cin >>id;
  if(id == current)
  { 
      mat.push_back(row);
   }
   else
   {
      std::cout << "different block" << std::endl;
      current = id;
   } 
   return 0;
  }

this code clearly only does part of the job and is doing a cin
rather than loading from the file

a vector is extensible and could be used to build a class for loading in your data it saves you having to use new and delete []

tetron 22 Junior Poster

You are not describing all of the details very thoroughly:

....i am well versed with the algorithm to do this...
PLease help!!!!

I am assuming that you are using visual studio
To read the input from a GUI - either write an application that is part of the GUI or operate from files: .bmp.

The easiest graphical representation to manipulate mathmatically is a bitmap. Windows will write directly to a bitmap before showing the object in an application like paint. and the Microsoft scribble tutorial is a reasonable place to start. GDI and Device Context are bith terms that take a fair bit of learning that are used for graphics in window

The tricky element can be saving bitmaps:

if you have a visual studio that has CImage this is useful as it lets you load and save bitmaps easily

If you are not able to use this look into the bitmap header structure

You do this so that you can visually check that your code is doing what is wanted.

1. get your algorithm implemented to work with a bitmap of the graph
screen shot manually cut and save to 24bit bitmap in paint.
2. sort out how you want the bitmap passed to your function
this will still be a bitmap

tetron 22 Junior Poster

One approach is to treat all of your input as chars say using std::srting

#include <string>
#include <iostream>

int main()
[
 std::string input;
 std::cout << "please enter data" << std::endl;
 std::cin >> input;

//using an int instead of sizetype f
//step over each char of input
int sz = (int) input.size();
for(int i(0); i < sz; ++i)
{
//current letter
  char c = input[i];
  if(c >= 'a' && c <= 'z')
  {
    //lower case
  }
  else if(c >= 'A' && c <= 'Z')
  {
     //upper case
  }
  else if(c >= '0' && c <= '9')
  {
    //digit
  }
  else
  {
     //? unexppected char 
   }
}
 return 0;
}

The idea is that you use the ascii charcater codes to decide
what each char is. Now you can convert the string of digits to a number if it is only digits will also
have to consider: decimal point (full stop) and minus

now there are other ways of handling the input and functions that will convert strings to numbers.

please help asap or and i need to make sure the input are integers only and character/letters

tetron 22 Junior Poster

You have an input of a number as a string because a float could have an unknown number of decimals

you want to convert that number to something that is a number within the computer so lets take the simple int example

std::string num("57657");

std::string::size_type sz = num;
//therefore sz = 5 as 
//57657 is 5 chars long

//num[0] = 5;
//num[1] = 7;
//num[2] = 6;
//num[3] = 5;
//num[4] = 7;

int val(0);
for(int i = 0; i < sz; ++i)
{
 //check that input is as expected
char c = num[i];
 if(c >= '0' && c <='9')
 {
    //have a digit to add
    //val +=  int(c - '0'); //new digit ie 5
    //but now know that we have another digit therefore
    // number is 10 times as big as
    val *= 10;
    val += int(c - '0');
  }
  else
  {
     //not a digit
  }
}
//so val should be 57675

the next step is to put the decimal point back in at the end

in real life you would just reverse the string but it would not
use your existing code and it is an assignment

if this is still confusing you could read up about std::string

Thanks for the detailed answer, but I can't even begin to comprehend it lol

tetron 22 Junior Poster

This is a fairly easy task if you restrict yourself to strings

//assuming number has nothing but "0123456789."
//it could have '-' but clean to just the digits
std::string number("31.2445");
//converting size_type to int
int sz =  (int) number.size();
int point = -1; 

//put the num into an int ignoring the point
int num(0);
for(int j = 0; j < sz; ++j)
{
 char current_letter = number[j];
  if(is_digit(current_letter) == true)
  {
     num * = 10;
      num += from_digit(current_letter);
  }
 else if(current_letter == '.')
  {
     if(point != -1)
     {
        std::cout << "second point found at: " << j << std::endl;
        break;
      }
      else
      {
        point = j;
      }
   }
}

//now num is 312445
//point is 2 and sz is 7

//reverse the number using a function
int r_num  = reverse(num);

//r_num should be 544213

//need to convert the point into a divider
double div(1.0);
for(int np(0); np < p; ++np)
{
  div * 10.0;
}

double d_r_num = r_num / div;

now this code is a little confusing and it converts an int
back to a decimal using a divider.

you have to still write

bool is_digit(char c);
int from_digit(char c);

in ascii the numbers go from '0' hint int i = '1' - '0'; i would be 1

This is the implementation method I'm looking for - I'm just not sure on how to convert to float and how to remove the point and reintroduce it again.

tetron 22 Junior Poster

you are asking sensible questions about how you would reverse the digits of a number.

And the reason why you are having problems is that it is not defined
behaviour - so to code it for non-integers requires a decision as to what is intended.

Option one treat it as a formatting exercise

read in the number as a std::string
identify any digits or decimal point:
ie

std::string num;
std::cout << "input number:" << std::endl;
std::cin >> num;
std::string digits("0123456789.");
std::string::size_type start = num.find_first_of(digits, 0);
std::string before_digits = num.substr(0, start);
std::string end = num.find_first_not_of(digits, start);
std::string after_digits = num.substr(end);
std::string to_reverse = num.substr(start, end - start);

std::string rev_num = before_digits + reverse(to_reverse) + after_digits;

now this code will reverse the digits by the use of [icode]reverse[/icode]

the idea is that
27.3
becomes
3.72
so you reverse the point as well

now if you need a number because of an assignment you can convert the string back to a float before you reverse

recursion is still tricky for the number as it really isn't a recursive task if you use decimals but you could find the decimal in a string
convert a string to an int
so say

"34.567"
find point p = 2 & num_digits = 5
conver to float->
34.567
remove point
*1000
34567
reverse recursively while > 0
76543
reintroduce "."
765.43

the other possible implementation
is reverse before and after the decimal point …

tetron 22 Junior Poster

cout
doesnt recognise arrays so you are outputting a pointer what you wanted to do is

#include <iostream>
int main() {
  int list[12] = {8,1,11,4,2,9,10,5,3,12,6,7};
//can go faster but this is easiest to read
for(int j =0 ; j < 12; ++j)
{
 std::cout<<list[j] << " ";
}  
//output a new line
std::cout << std::endl;
return 0;
}
LeoC++ commented: Thanks!! Great fast accurate answer! +0