vijayan121 1,152 Posting Virtuoso

Gah!!! No matter what I do, every time I make a correct implementation of this priority queue, when I try to run my program, I get this:
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Assertion Failed!
Program: ...
File: c:\program files\microsoft visual studio 8\vc\include\algorithm
Line: 2025
Expression: invalid operator<
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
---------------------------
Abort Retry Ignore
---------------------------

No matter what little tricks I try!

My current predicate looks like this:

struct comp
{
bool operator() ( const Node* first, const Node* second ) const
{
if (first->getHeuristic() > second->getHeuristic()) {
return true;
}
else if (second->getOrder() < first->getOrder()) {
return true;
}
else {
return false;
};
}
};

the only way this thing will run is if I make the < in the first else if statement a >, which orders them backwards. What the heck is going on???

i had said in my earlier reply

remember that the predicate must be a relation that is asymetric,
irreflexive and transitive; ie. one that imposes a strict oredering
on the sequence.

because it is important to understand it.

take two nodes
node_a ( getHeuristic returns 10, getOrder returns 6) and
node_b ( getHeuristic returns 11, getOrder returns 5)

comp()(a,b) returns true
if (first->getHeuristic() > second->getHeuristic()) // false

vijayan121 1,152 Posting Virtuoso

Hi!

How can I read all files in a directory, when I don't know which files are
there?

Sincerely
Jasmina Jeleva!

you could use the boost filesystem library.
it is portable across unix, linux and windows.

here is a sample program which prints the names of all files in a directory.

#include <iostream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem; 
using namespace std;

void show_files( const path & directory, bool recurse_into_subdirs = true )
{
  if( exists( directory ) )
  {
    directory_iterator end ;
    for( directory_iterator iter(directory) ; iter != end ; ++iter )
      if ( is_directory( *iter ) )
      {
        cout << iter->native_directory_string() << " (directory)\n" ;
        if( recurse_into_subdirs ) show_files(*iter) ;
      }
      else 
        cout << iter->native_file_string() << " (file)\n" ;
  }
}

int main()
{
    show_files( "/usr/share/doc/bind9" ) ;
}

on my machine it produced the following output.

g++ -std=c++98 -Wall -I/usr/local/include file_system.cpp /usr/local/lib/libboost_filesystem.a ; ./a.out

/usr/share/doc/bind9/arm (directory)
/usr/share/doc/bind9/arm/Bv9ARM.ch01.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch02.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch03.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch04.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch05.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch06.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch07.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch08.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.ch09.html (file)
/usr/share/doc/bind9/arm/Bv9ARM.html (file)
/usr/share/doc/bind9/misc (directory)
/usr/share/doc/bind9/misc/dnssec (file)
/usr/share/doc/bind9/misc/format-options.pl (file)
/usr/share/doc/bind9/misc/ipv6 (file)
/usr/share/doc/bind9/misc/migration (file)
/usr/share/doc/bind9/misc/migration-4to9 (file)
/usr/share/doc/bind9/misc/options (file)
/usr/share/doc/bind9/misc/rfc-compliance (file)
/usr/share/doc/bind9/misc/roadmap (file)
/usr/share/doc/bind9/misc/sdb (file)
/usr/share/doc/bind9/CHANGES (file)
/usr/share/doc/bind9/COPYRIGHT (file)
/usr/share/doc/bind9/FAQ (file)
/usr/share/doc/bind9/README (file)

vijayan121 1,152 Posting Virtuoso

However, if I use the correct predicate: ...

the predicate you have written (as the correct one) is equivalent to

bool operator() ( const Node* first, const Node* second ) const
{
  return first->getHeuristic() > second->getHeuristic() ;
  // in all other cases you are returning false
}

the order is not involved at all.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

Some people have argued that ++i yields more efficient assembly code. When I checked, they were the same. In this situation, it doesn't matter.

in this specific case it really does not matter. When applied to primitives such
as int or char, they are indistinguishable in terms of efficiency. When applied
to objects of a user defined type the difference can be significant; the prefix
version avoids the creation of an anonymous temporary.

try this code:

int main()
{
  struct A
  {
    A( int ii ) : i(ii) { cout << "A::constructor\n" ; }
    A(const A& that ) : i(that.i) { cout << "A::copy_constructor\n" ; }
    ~A() { cout << "A::destructor\n" ; }
    A& operator++() // prefix
    { ++i ; return *this ; }
    A operator++(int) // postfix
    { A temp(*this); ++i ; return temp ; }
    operator int() const { return i ; }
    int i ;
  };
  cout << "-------------  start -----------------------------\n" ;
  A a1 = 100, a2 = 100 ;
  cout << "a1: " << a1 << "\ta2: " << a2 << '\n' ;
  cout << "-------------  prefix++  ------------------------\n" ;
  int i = ++a1 ; 
  cout << "a1: " << a1 << "\ti: " << i << '\n' ;
  cout << "-------------  postfix++  -----------------------\n" ;
  i = a2++ ;
  cout << "a2: " << a2 << "\ti: " << i << '\n' ;
  cout << "-------------  done -----------------------------\n" ;
};

and here is the output:
------------- start -----------------------------
A::constructor
A::constructor

vijayan121 1,152 Posting Virtuoso

socket++ is a library that i have used. it works resonably well. it has a distinct c++ feel about it;
sockets in the library have the same interface as the streams in the iostream library. here is the link:
http://www.linuxhacker.at/socketxx

vijayan121 1,152 Posting Virtuoso

I need help verifing. ......
Create a new function to verify the numeric input values. This function will be in a separate source file.
verifyValue.cpp

This function will determine if a string contains a valid numeric value. It will return true or false.

bool verify_value( const char* cstr )
{
    if(  ( *csr ==  '-'  ) || ( *cstr == '+' ) ) ++cstr ; // one leading + - is ok
    while( cstr != 0 ) 
        if( !isdigit(*cstr++) ) return false ;
    return true ;
}

note: checks only for decimal digits, see isxdigit if hex is to be supported.
asssumes there are no leadin/trailing spaces.

vijayan121 1,152 Posting Virtuoso

Actually, I have one more quick question. I'd actually like this to be a priority_queue of Node* (pointers to Node), but if I do that, then it sorts the queue using pointer arithmetic. So the Node*s with the lower addresses are put at the front and the higher ones are at the back. Is there any way for me to define a custom way to sort them in the Node class? Like, can I overload the "<" operator for just Node pointers somehow? Know what I mean?

pointers are a standard type and you can not define how pointers are to be
compared anywhere. however, you can tell the priority_queue of Node*
how you want priorities to be compared.
a. write a binary predicate to compare nodes

struct compare_node_pointers
{
  bool operator() ( const Node* first, const Node* second ) const
  {
    // return true if first has lower priority than second.
   //  false otherwise.
  }
};

b. specify the predicate to the priority_queue

typedef std::priority_queue< Node*,  std::vector<Node*>, 
                              compare_node_pointers > my_prioroty_queue ;
// use object(s) of type my_prioroty_queue where required

remember that the predicate must be a relation that is asymetric,
irreflexive and transitive; ie. one that imposes a strict oredering
on the sequence.

vijayan121 1,152 Posting Virtuoso

make your operator< const correct.

bool Node::operator< ( const Node&) const
vijayan121 1,152 Posting Virtuoso

the code i posted will cause a buffer overflow on most compilers on a 32 bit architecture.


No -- it will create buffer overflow on every ansi standard compilant compiler, which is almost every c compiler in the world.

true. i stand corrected.
i should have said ".. will cause a buffer overflow into a[0] on most
compilers on a 32 bit architecture."

vijayan121 1,152 Posting Virtuoso

Why is it giving me this?

if (temp_each_day = NULL)

the compiler would have given a warning for this.
tip: set the warning level of the compiler to the highest available, and pay attention to the warnings.
you would save yourself a great deal of effort and time.

vijayan121 1,152 Posting Virtuoso
if (temp_each_day = NULL)
        printf("Error opening input file. \n");

The = in the above code should be replaced by == if what you want to do is comparision.

that is clearly the error. once you assign NULL to temp_each_day,
a. the if block will not execute.
b. fclose(NULL) will assert and an assertion wil fail on exit if fclose is not called.

vijayan121 1,152 Posting Virtuoso

since the debud assertion that fails is:

Debug Assertion Failed!
Program: F:\Debug\lab1431.exe
File: fscanf.c
Expression: stream != NULL

the error is that at a place where the
stream was expected to be NULL, it is not NULL. stream (in the FILE structure)
would be NULL after the file has been closed.
remember that fscanf can corrupt memory if your format specifiers are incorrect.

vijayan121 1,152 Posting Virtuoso

endl is not a character, it's a macro which: a) inserts a newline '\n' into the output buffer b) flushes the output buffer.

endl is a function

template<typename CHARTYPE, typename TRAITS> 
  basic_ostream<CHARTYPE,TRAITS >& endl( 
                             basic_ostream<CHARTYPE,TRAITS>& stm )
  {
      stm << '\n' ;
      returm stm.flush() ;
  }

this kind of function is called an ostream manipulator in c++
infact, any function that we write taking a single argument which
is a reference to a stream and returns a reference to a sream is a
manipulator for the stream.

Realistically, you should only be using endl when you actually need the output buffer flushed, because otherwise you're just cutting down your program's performance.

very true

vijayan121 1,152 Posting Virtuoso

close the file: fclose

vijayan121 1,152 Posting Virtuoso

i tend to use an un-named enum for integral constants because
a. they are as effective
b. they can appear in places where const variables can not.

struct time_of_day
{
   enum { HOURS_PER_DAY = 24, /* ... */ };
   // ...
};

in a compliant compiler, this is possible

struct time_of_day
{
   static const int HOURS_PER_DAY = 24 ;
   // ...
};

in the header.
and in the implementation file,

const int time_of_day::HOURS_PER_DAY ; // do not initialize here too!

i am too lazy to do this much work; the anonymous enum is simpler.

vijayan121 1,152 Posting Virtuoso

the code i posted will cause a buffer overflow on most compilers on a 32 bit architecture.
you may need to increase the size of the array to 32 on 64-bit.
the printf should illustrate that overflow has occurred (into the first element of array a)

vijayan121 1,152 Posting Virtuoso

a. read each line in the file into a std::string
b. parse the line that was read using a std::istringstream

enum { MAX_ITEMS_PER_LINE = 25 };
  ifstream file("file_name - perhaps picked up from argv[1]") ;
  string line ;
  while( getline( file, line ) )
  {
    istringstream stm(line) ;
    int NOMBRE, ADJ[MAX_ITEMS_PER_LINE] = {0}, 
                           PERTE[MAX_ITEMS_PER_LINE] = {0} ; 
    int count = 0 ;
    stm >> NOMBRE ;
    while( stm >> ADJ[count] )
    {
      stm.ignore( line.size(), ',' ) ; // eat the comma
      stm >> PERTE[ count++ ] ;
    }
    // do whatever with the info - count == number of items read
  }
vijayan121 1,152 Posting Virtuoso

try

int a[16] = { 0 }, b[16] = { 0 } ;
  b[16] = 25 ;
  printf( "%p -> %d   %p -> %d\n", a, a[0], b, b[0] ) ;

notes
a. an all hw architectures that i know of, the stack grows from higher towards
lower addresses.
b. most compilers will allocate more memory than seems is necessary
for data. (why?)
c. play around with the size of the array and the storage class of the array and
try to figure out what happens.
d. generate a lising with assembly, source and machine code to see what really
happens.
e. if possible, try to use different compilers and repeat the experiment
.

vijayan121 1,152 Posting Virtuoso

getc_unlocked() and getchar_unlocked() functions conform to IEEE Std 1003.1-2001
(POSIX.1). so every *nix (mac is *nix below the hood) should have them as part of the
base system. (in linux, it would be in glibc.)

"getc_unlocked() and getchar_unlocked()functions are equivalent to getc() & getchar()
respectively, except that the caller is responsible for locking the stream with
flockfile(3) before calling them. These functions may be used to avoid the
overhead of locking the stream for each character, and to avoid input being
dispersed among multiple threads reading from the same stream."
-- from freebsd man pages.
i guess most *nix implementations would implement getchar as
flockfile, getchar_unlocked, unflockfile

vijayan121 1,152 Posting Virtuoso

you need the framework for the IDE.
the compiler itself (and link etc.) do not.
if you are willing to work from the
command line using cl.exe, link.exe,
nmake.exe, you do not neet the framework.

vijayan121 1,152 Posting Virtuoso

the parser for the command line seperates
arguments by looking for whitespaces. so if
the command line parameters do not have
whitespaces in them thins work fine.
putting quotes indicates that everything
inside the quotes, including white spaces
are part of the single arg.
since argv[0] is the full path to the
executing program, it is not picked up
from the command line.
notepad.exe (and most microsoft programs)
use the win32api GetCommandLine function.
this gives the entire command line as a single
string which is then parsed as required by the
program.

vijayan121 1,152 Posting Virtuoso

This works, which is what Vijayan posted. All I did was replaced int with longlong (VC++ 2005 used __int64)

not really necessary.
both 999 and 3*9*9*9 (max possible values)
are <= 1000.
int wouls suffice

vijayan121 1,152 Posting Virtuoso

comparing a signed value with an unsigned
value has a logical problem.

int si = -7 ;
unsigned int ui = 68 ;
( si < ui ) ; 
// true if interpreted as si < signed(ui)
// false if interpreted as unsigned(si) < ui

at the very least, the behavoiur is
'implementation dependant'

however, if the signed value is >= 0, and
the unsigned value is less than half of the
possible max value for the type, there
would be no differences between
implementations.

Daniel E commented: Makes sense and helpful +1
vijayan121 1,152 Posting Virtuoso

very true. whenever i try to write C,
a bit of it comes out as C++

vijayan121 1,152 Posting Virtuoso

> You cannot use C to solve this problem.
Of course you can, it just takes an additional library to help you do all the hard stuff.
http://gmplib.org/

Or if you're only interested in a couple of math ops, then you could work out how to do long arithmetic in your own code instead.

#include<stdio.h>

int value_digits( int a, int b, int c ) { return a*100 + b*10 + c ; }
int value_sum_power( int a, int b, int c ) { return a*a*a + b*b*b + c*c*c ; }

int main()
{
  for( int a=0 ; a<10 ; ++a )
      for( int b=0 ; b<10 ; ++b )
          for( int c=0 ; c<10 ; ++c )
          {
            int number = value_digits(a,b,c) ;
            if( number == value_sum_power(a,b,c) )
              printf( "%d\n", number ) ;
          }
  return 0 ;
}
Aia commented: Great job -Aia- +1
vijayan121 1,152 Posting Virtuoso

char temp[length];
the error is that length is not a
constant known at compile-time.

(this is not an error in C99, but
is an error in standard C.)

vijayan121 1,152 Posting Virtuoso

this is what the linux man pages say (in part) about rand(3):

" ... The versions of rand() and srand() in the Linux C Library
use the same random number generator as random() and sran­
dom(), so the lower-order bits should be as random as the
higher-order bits. However, on older rand() implementa­
tions, the lower-order bits are much less random than the
higher-order bits.

In Numerical Recipes in C: The Art of Scientific Computing
(William H. Press, Brian P. Flannery, Saul A. Teukolsky,
William T. Vetterling; New York: Cambridge University
Press, 1992 (2nd ed., p. 277)), the following comments are
made:
"If you want to generate a random integer between 1
and 10, you should always do it by using high-order
bits, as in

j=1+(int) (10.0*rand()/(RAND_MAX+1.0));

and never by anything resembling

j=1+(rand() % 10);

(which uses lower-order bits)."

Random-number generation is a complex topic. The Numeri­
cal Recipes in C book (see reference above) provides an
excellent discussion of practical random-number generation
issues in Chapter 7 (Random Numbers). ..."

vijayan121 1,152 Posting Virtuoso

THERE IS A SERIOUS ERROR IN THE PREVIOUS POST.

there is a well known algorithm to
do this without having to pass through the entire sequence:

string random_l[ine( ifstream file )
{
   string line ;
   int nlines = 0 ;
   while( getline( file, line ) )
      if(  ( rand() % ++nlines  ) == 0 ) break ;
   return line ;
}

IT SHOULD BE
there is a well known algorithm to
do this without having to copy the entire sequence
into a buffer having random access :

string random_line( ifstream file )
{
      string line ;
      string selected_line ; // added
      int nlines = 0 ;
      while( getline( file, line ) )
         if(  ( rand() % ++nlines  ) == 0 ) // break ;
                  selected_line = line ;      
    return selected_line ;
}
vijayan121 1,152 Posting Virtuoso

the basic problem here is that we need to select one item at random
when we do not know beforehand how many items there are. the most
common example of this in real code is when a random element has to
be picked from a list (size unknown). there is a well known algorithm to
do this without having to pass through the entire sequence:

string random_line( ifstream file )
{
  string line ;
  int nlines = 0 ;
  while( getline( file, line ) )
     if(  ( rand() % ++nlines  ) == 0 ) break ;
  return line ;
}

the variable nlines counts the number of lines as they are read.
for any line, rand() % ++nlines == 0 is true with probability
1 / nlines. the first line is initially selected (with probability 1),
the second line replaces it with probability 1/2, the third line will
replace the survivor (either line one or line 2, each of which are
equally likely) with probability 1/3, and so on.therefore, for each
of the nlines lines seen so far is selected with probability
1/nlines.

if i remember right, this was first seen widely in some code
written by brian kernighan.

vijayan121 1,152 Posting Virtuoso

I am a student in Bogazici University/Turkey. We have a project and I want to change the cursor position but there is a problem. Our teachers are using Microsoft Visual C++ 2005 Express Edition. In this compiler there is no windows.h header. What can I do?

visual c++ express does not ship with the platform sdk (for which windows.h is the main header). however, you can download and install the platform sdk for free. and you need to set up the visual c++ environment to use it. for clear step-by-step instructions on how to do this, see:
http://msdn.microsoft.com/vstudio/express/visualc/usingpsdk/

vijayan121 1,152 Posting Virtuoso

oh... and no other database format to my knowledge allows for multimedia, or files in general to be stored within a field, which is the purpose for designing this structure. If i am wrong PLEASE let me know.

you mean no other open source database.

this is what oracle claims about interMedia.
'With interMedia, you can type columns of relational tables as containing media. For example, you can take an existing human resources table that contains name, address, and other traditional data, and add an image column to contain a picture of an employee. Or you could take a product table and add a video column to show products in use. There is not limit on the number of media columns that can be added to a table. Through this mechanism, media can be easily associated with traditional, relational data.'

is this just hype by oracle?

vijayan121 1,152 Posting Virtuoso

you forgot to terminate the definition
of the class with a ;

[/B]class __gc whatever
{
} // need a semicolon here
vijayan121 1,152 Posting Virtuoso

another possibility is that the variable or
function is defined in more than one file.
in this case your error message would look
like
'multiple definition of <identifier>'
or
'one or more multiply defined symbols'

if you tried to declare a variable in another file

extern int first = 0 ; // definition - multiply defined
  extern int second ; // declaration - ok
vijayan121 1,152 Posting Virtuoso

there are two ways to simulate returning
many values from a function:
a. return a struct with more than one
member variable. std :: pair<> is handy
if you want to return a pair of values.
b. pass a modifiable referance (or pointer
to non const) as a parameter, which
the function can fill up.
if the types of all the values returned are
the same, u could also return a collection;
eg: std::vector

vijayan121 1,152 Posting Virtuoso

IMO, sometime STL classes are more hassle than they are worth. One such occassion is during a class when the instructions are to use an array. Another is when the upper bounds of the array are given. And another is when the user has no idea what a template or an iterator is.

ifstream fin("inputFile.txt"); //to read from file
ofstream fout("outputFile.txt"); //to write back to file 
string input[100]; //to hold input
int i = 0;  //to keep track of how many strings actually read in, may be less than max possible.
 
//validate files are open here
 
//read input file one string at a time, adding it to the array in the appropriate index
while(getline(fin, input[i]))
   i++;
 
//write to output file (frontwards for this demonstration) one string per line
for(int x  = 0; x < i; ++x)
      fout << input[i] << endl;
 
//close files here

prefer an array to a vector to bring the all the lines of a text file into memory?
well, i suppose everyone has a right to their opinion.

vijayan121 1,152 Posting Virtuoso

u need to use a vector<string>, not
vector<int>.

and u need to use getline to read in
eah line till eof. the file is read from
begin to end (forward). after inserting
the lines into the vector, iterate
backwards in the vector (from the
last element to the first).

do not worry about the number of
lines (as long as it is not impossibly
large); when u call push_back the
vector resizes itself. start with an
empty vector; after adding all the lines
(push_back), the size() method of the
vector will tell u how many strings have
been added. this is useful if u want to
iterate over it like a c style array; start
with pos size()-1 and end at pos zero
to iterate backwards.

vijayan121 1,152 Posting Virtuoso

modify the function to

int countchar( const char list[], char what )
{
  int i=0, count=0 ;
  for( ; list[i] != 0 ; ++i )
        if( list[i] == what ) ++count ;
  return count ;
}
vijayan121 1,152 Posting Virtuoso

to fix the compiler error:
u need to declare the function before u
call it. add the following anywhere before
the call.

void backward(vector <int> vect) ;

a vector is really a dynamically resizeable
array; paasing it by value is not a good
idea at all.
(u are copying a large collection!)
in general, for any user defined type,
prefer passing by const referance instead
of by value. so i would also suggest u
change the signature of backward to

void backward( const vector<int>& vect ) ;

were u not trying to read strings (lines)
from the file (not integers) in the original
post?

vijayan121 1,152 Posting Virtuoso

a. read the lines and insert it into a vector

ifstream file("customer.txt") ;
string rec ;
vector<string> records ;
while( getline(file,rec) ) 
    records.push_back(rec) ;

b. iterate over the vector backwards to
access the redords in reverse order

ofstream outfile("custFileCopy.txt") ;
  std::copy( records.rbegin(), records.rend(),
        std::ostream_iterator<string>(outfile) );

you can do this only if the file is small enough;
for very large files memory may not be sufficient.
u could however read the file in parts (say 1000 records),
create intermediate output files (as above) and then
merge them in reverse order of creation.

*** note: i had not seen Lerner's post; it came in while i was
typing in the reply. so this is just a repetition of what was
suggested in that post

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

since we are using std::string, why not

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str ;  cin >> str ; 
  const string vowels = "aeiouAEIOU" ;
  int n_vowels = 0 ;
  for( string::size_type pos = str.find_first_of(vowels) ; pos != string::npos ;
        pos = str.find_first_of(vowels,pos+1) )  ++n_vowels ;
  cout << "vowels: " << n_vowels  << "\nconsonants: " 
          << str.size()-n_vowels    << '\n' ;
  return 0 ;
}
~s.o.s~ commented: Yes a good approach but too much for a beginner..;) - ~s.o.s~ +15
vijayan121 1,152 Posting Virtuoso

ncurses (or curses) is installed by default by
most linux distros. try man curses to check.

install ncurses-development package if
it is not already installed.

while writing code,

[B]#include <ncurses.h> [/B]// or <curses.h>
[B]int main()[/B]
[B]{
    initscr() ; [/B]// must be called first[B][B]
    cbreak() [/B][/B][B]// [/B]disable the buffering
     // required to get a character immediately
     // without waiting for return key.
 [B]
    noecho();[/B]   // only if u want to suppress 
      // echo of input keys
  
    [B] keypad(stdscr, TRUE);[/B]   // only if u want
     // to read special keys (delete,arrow keys etc.)

     // to read a character, use
     [B]int getch(void) ; 
 [/B]   // normally [B]getch[/B] waits till a 
    // key is hit. to work in a 
    // nonblocking manner, call
 [B]  // nodelay(stdscr,   TRUE) ;
 [/B]  // in this case getch will return 
   // [B]ERR[/B] if key input is   not available.
 
    [B]endwin()[/B] // must be called before exiting
    // to restore the terminal settings.
   
   return 0 ;
}

compiling/linking:
either gcc. -lncurses your_program.c
or gcc your_program.c libncurses.a

link statically to the ncurses library
if u want to run your program on machines
where ncurses is not installed.

vijayan121 1,152 Posting Virtuoso

if you are using c++ we can write portable code

std::cin >> std::noskipws ;
char ch ; 
std::cin >> ch ;
if( ch == '\t' ) /* ... */ ;// tab
else /* ... */ ; // something else
vijayan121 1,152 Posting Virtuoso

Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin - John Von Neumann (1951).

for more information see:
http://www.random.org/randomness/

if pseudo-randomness is all that is required, a good c++ library is
the boost random number library.
for more information on these, see
http://www.boost.org/libs/random/random-generators.html
http://www.boost.org/libs/random/random-distributions.html
http://www.boost.org/libs/random/random-concepts.html

vijayan121 1,152 Posting Virtuoso

u could memory map the file (unix mmap/mmap64 or windows CreateFileMapping/MapViewOfFile) to reduce the i/o overhead (or use a large file buffer with C/C++ file i/o).

vijayan121 1,152 Posting Virtuoso

one way to do this is
a. pad the matrix with null chars on all four sides.
b. search for the word in each row using strstr.(EAST)
c. rotate the matrix by 90 degrees and repeat (NORTH)
d. rotate the matrix by 90 degrees and repeat (WEST)
e. rotate the matrix by 90 degrees and repeat (SOUTH)

here is the code. in this example, the co-ordinares printed
are in the rotated matrix, (number of rotations are given in
paranthesis).
your task: translate these to the original (unrotated) co-ordinares.

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

enum { WIDTH = 8 };
void rotate( char (&array)[WIDTH][WIDTH] ) // rotate array by 90 degrees anti-clockwise
{
  for ( int i=0, mi=WIDTH ; i < mi-- ; ++i )
    for ( int j=0, mj=WIDTH ; j < mj--; ++j )
    {
      char tmp = array[i][j];
      array[i][j] = array[mj][i];
      array[mj][i] = array[mi][mj];
      array[mi][mj] = array[j][mi];
      array[j][mi] = tmp;
    }
}

int main(int argc, char *argv[])
{
  const char* const puzzle[] =
  {   "ebzrys",
      "rsygaf",
      "caakce",
      "avcmre",
      "nolnoc",
      "droguz"
  };
  const char* const words[]={"ercan", "olcay", "conlon", "oguz", "cprog"};
  const int NWORDS = sizeof(words) / sizeof(*words) ;
  char grid[WIDTH][WIDTH] = { {0} };
  for( int i=0 ; i<WIDTH-2 ; ++i ) strcpy( grid[i+1]+1, puzzle[i] ) ;  
  
  for( int n=0 ; n<5 ; ++n )
  {
    cout << words[n] ;
    char* found = 0 ;
    for( int i=1 ; i<WIDTH-1 ; ++i )
    {
      for( int nrot=0 …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

Index = 1;
should be inside the outer while loop.

vijayan121 1,152 Posting Virtuoso

for your specific problem:
1-100 arrays of size 10 with randomly distinct numbers from (0-9)
2-100 arrays of size 50 with randomly distinct numbers from (0-49)
3-100 arrays of size 100 with randomly distinct numbers from (0-99)
4-100 arrays of size 200 with randomly distinct numbers from (0-199)

u could fill an array of size N with values
0, 1, 2, ..., N-2, N-1
and then just do a std::random_shuffle on it.
(after seeding the random number generator)

Salem commented: Excellent suggestion, but probably too advanced to hand in as noob homework +6