tetron 22 Junior Poster

Yikes I only just realised that I had lost all of the formatting
for multiplication example :(

Should have looked more like:

12345678
x30978793

the answer can be found a digit at a time:

if you reverse one of the numbers
30978793 -> 39787903

then the last digit of the answer is:

1 2 3 4 5 6 7 8
              |
              3 9 7 8 7 9 0 3

is the last digit of 8 * 3 = 24

so a 4
then we have a 2 that we need to carry:
shift the numbers along by one to find next digit
carry = 2

1 2 3 4 5 6 7 8
            | |
            3 9 7 8 7 9 0 3

and the next digit is the last of

2 + 7*3 + 8*9 = 95

5
and then there is a carry 9

shift the numbers along by one
carry = 9

1 2 3 4 5 6 7 8
          | | |
          3 9 7 8 7 9 0 3

9 + 6*3 + 7*9 + 8*7 = 146

the point being that you just remember a 3-digit number at most
if you right down the answer a digit at a time
so:
9 + 18 = 27
27 + 63 = 90
90 + 56 = 14:6

tetron 22 Junior Poster

>> While that is a correct solution

I beg to differ. Thats far from a correct solution.

I will expand on why this is true in a second.

First an aside
(
firstPerson -> did you find thishttp://www.daniweb.com/forums/thread260788.html
I expected at least a put down for not getting your signature :)
)

back on topic:

for (q=n,i=1;q!=0;r[i++]=q%10,q=q/10);

There are several rasons why this is wrong

1 - it can overflow r[10]
2 - if you are not going make code readable why are you starting
from i = 1 and not i = 0;
3 - the compiler will not necessarily optimise the code correctly
4 - the only reason for reducing the number of lines of code is to
make it more maintainable and in this instance this is not the case
5 - example code should always be readable
6 - stop condition of != 0 on something that you are changing is dangerous > 0 is better as with n being negative there is a risk of %10 being not the digit -1%10 should return 9

there is a lot of hidden behaviour being used such as
q = q / 10 is relying on the fact that q = q/10 is performing a floor operation with it being an int. But mathematically this is not what the code is saying

in my opinion a for loop …

tetron 22 Junior Poster

One point that I thought I ought to bring up is that if you have
a non integer number such as a decimal you can still find the digits but the stop condition is tricky

so while

int i(142), n(10);
int remainder =  i%10;
i = (i - remainder) /n;

can be put in a loop upwards you don't catch decimals if it is changed to double i(1.42) This makes the approach of using a string preferable
you can check for '-' and '.'
and either get the digits one at a time or if
this is an assignment convert it to a number
but now if

//need to include <string>
std::string number;
std::cin >> number;
int num_letters  = number.size();
if(num_letters > 0)
{
    if(number[0] == '-')
    {
        //minus
     }

 //search to find in string
   if(std::string::npos != number.find('.', 0))
   {
      // have a point
      int pos_of_point = number.find('.', 0);
    }
   
}
tetron 22 Junior Poster

well you have found the fibonaci series of numbers with a formula

if you place this code into a function to find the fibonaci numbers.

Here are two approaches:

1 - write a function that stores all of the fibonaci numbers between
a lower and upper limit.

this would best be achieved with a vector

2 - write an method to check if a number is a fibonaci_number bool is_fib_num(int to_check); if you do a while loop like you have but check

bool is_fib_num(int num)
{
//in your function
ret = false;
   while(c < num)
  {
//add your existing code from your while loop here
     if(c == num)
    {
      ret =  true;
      break;
    }
 }
}
return ret;

now you need to go through main to check each number until you
have 15

int n = 0;
int num = 0;
while(n < 15)
{
   if(false == is_fib_num(num))
   {
     //not a fibonaci
    cout << num << endl;
    ++n;
  }
++num;
}
tetron 22 Junior Poster

There are a few problems with your code

first off it is a good idea to work out the logic and
method you want on paper first because I suspect
that the book method has resulted in you using a method that
has confused you a little

log10(1) == 0
log10(0) == error

luckily you avoid the error but it helps if you use temporaries

double power2 = pow(2, row);
int ndigits = ceil(log10(power2);

it would allow you to print out numbers to see what is happening
at stages and reduces what you need to type

so the ones are being lost because you have not decalred what to do if log10(power2) == 0; which happens when power2 = 1

the more major thing is that you are using doubles in your for
loops it is not a good choice stick to int, unsigned int or iterators.

the for loop has three things that go in the backets

initial conditions;
condition to do;
action

the condition to do has to be true for a cycle to happen
so

intialise
while(end condition)
{
action;
}

if you look at line 20
this needs row == column to be true
to run otherwise it stops this is not what you want;

if you are using a double stop condition it is much better to use …

tetron 22 Junior Poster

Well, it's been five days since the challenge was issued, so I'll post my shot at a solution:

Not sure that I found all the rules very natural
but since I did a rough try I will include mine
to make others feel better:)

I changed the logic of this and have not
even tested with a compiler...

I find the first char that is different
this says that there is a precidence

special cases are

num : num
space : num
num : space

otherwise normal char comparison

methods used are:

typedef std::string::iterator str_it;
//false means no digit to find
bool skip_to_digit(str_it &cur, str_it &it_stop);
//both d1 & d2 pointing to a digit
bool first_number_bigger(str_it &it1, str_it &it1_stop,
str_it &it2, str_it &it2_stop, bool def = false);
bool is_digit(char c);

natural find

str_it it1(a.begin()), it2(b.begin());
str_it it1_stop(a.end()), it2.end());
do{
	
 char c1(*it1), c2(*it2);
 if(c1 != c2)
 {
   bool current(false);
   if(is_digit(c1))
   {
     if(c2 == ' ')
     {
      	 if(advance_to_digit(it2, it2_stop))
       	{
	   //if the same c1 bigger
	   return first_number_bigger(it1, it1_stop, it2, it2_stop, false);
       	}
       	return false;
     }
     else if(is_digit(c2))
     {
	//both numbers same ret = false
	return first_number_bigger(it1, it1_stop, it2, it2_stop);
     }
   }
   else if(c1 == ' ' && is_digit(c2))
   {
     if(advance_to_digit(it1, it1_stop))
     {
	//both are numbers if same c2 bigger
	return first_number_bigger(it1, it1_stop, it2, it2_stop);
     }
     return true;
   }

   return (c1 > c2);
 }

}
while(++it1 != it1_stop && ++it2 != it2.stop);

//so far the same final check
return …
tetron 22 Junior Poster

#3 = As fast as a bat out of hell

be warned such code stays angry for a long time and can bite:)

Only do this if you want to get PhD!

I have purposefully given only sketchy details

1. because I agree with WaltP's 3rd rule of procrastination
2. It gets messy
3. I am not sure if it could be used to break an existing cypher


You need specialist algorithms and your benchmark is method 2
and it gets left for dust the more randomly the selection of digits
from the power is wanted

This would be if you were trying to use a brute force decryption
for which there will be even stronger techniques

in base-10 3^100
looks messy but in base-3...

x^13 look at the last digit...

This means that the sum of powers is in fact not a random sequence

the nth digit can be found through extending what was touched on
about adding repeating sequences to convert the calculation of finding
the nth digit of any single digit number to any power in under 1000 FLOPs

If you want to look at the sums of powers

the interactions between the digits can be expressed as functions of the nth digit
equation and the modulo being used in the previous method can sum all of the occurences
of a particular digit.

tetron 22 Junior Poster

Standard maths +

although you will not get a large improvement
for calculating serires

suppose you want to add some huge self powers and get the final 10 digits
say 124953276509676^124953276509676

then the ten_digits class even if extended will take a long time

there is a piece of mathematics called a polynomial expansion

for the trinomial

(A * x^2 + B * x + C)^m


you get C^m + m!/(0! * 1! * m - 1!) * B*x + C^m-1


The exact mathematics can be found easily the thing to note

is ABCD for a base ten number =
A*1000 + B*100 + C *10 + D
(10^3) (10^2)

and the
trinomial term

m!/((m-i-j)! *i! *j!) C^(m-i-j) * B^i * x^i * A^j *x^2j

needs only be found for
2j+i < 10
and for the bottom 10 digits as withthe simple example

now though powers to the modulo repeat

so for 3

3 9 7 1 3 9
0 2 2 0 0


the lower line is the carry

with this method you only need the 10 digit sequences
for the single digits

this can be reduced to a sequence that I won't go into
here

but a computational approach is there is an initial sequence
that will not repeat
and a stable …

tetron 22 Junior Poster

Now the implementation of the the .cpp
completes the calculation although the display is messy
I have included it so people can use the code should they so wish

#include "ten_digits.h"

ten_digits::ten_digits(int upper, int lower)
:hundred_thousands(upper), ones(lower), i_100000(100000)
{
}

void ten_digits::times_by(int small_int)
{
	int temp = ones * small_int;
	ones = temp%i_100000; //bottom 5 digits
	int carry((temp - ones) / i_100000);//what are the overflow digits
	hundred_thousands = (hundred_thousands * small_int + carry) % i_100000;
}

ten_digits & ten_digits::operator +=(const ten_digits &td)
{
	ones += td.get_ones();
	hundred_thousands += td.get_hundred_thousands();
	if(ones > i_100000)
	{
		//have a carry of 1
		ones -= i_100000;
		++hundred_thousands;
	}
	hundred_thousands = hundred_thousands %i_100000;
	return *this;
}

std::string ten_digits::get_display_string() const
{
	std::string reverse_ret("");
	int half_digits(5);
	int current(ones);
	for(int i(0); i < half_digits; ++i)
	{
		int temp(current%10);
		char digit(temp);
		digit += '0';
		reverse_ret += digit;
		current /= 10;
	}
	current = hundred_thousands;
	for(int j(0); j < half_digits; ++j)
	{
		int temp(current%10);
		char digit(temp);
		digit += '0';
		reverse_ret += digit;
		current /= 10;
	}
	
	//need to reverse
	std::string ret;
	std::string::reverse_iterator r_it_stop(reverse_ret.rend());
	for(std::string::reverse_iterator r_it(reverse_ret.rbegin()); r_it != r_it_stop; ++r_it)
	{
		ret += *r_it;
	}
	return ret;
}

bool ten_digits::raise_to_power(int pow)
{
	bool ret(true);
	if(pow == 0)
	{
		hundred_thousands = 0;
		ones = 1;
	}
	else if(hundred_thousands == 0 && pow > 0)
	{
		int small_int(ones);
		for(int i(0); i < pow; ++i)
		{
			times_by(small_int);
		}
	}
	else
	{
		ret = false;
	}
	return ret;
}
tetron 22 Junior Poster

There is probably a joke in the comment that I am missing
but this post is going to give the design approaches to solving
the problem posed by FirstPerson in his signature:

find the last ten digits of
x^x (x raised to the power of x)
for all the positive 0dd numbers below 1000

1^1 + 3^3 + 5^5 ..... +997^997 + 999^999

The first thing to realise is that this is a
computationally small problem and the complete
answer can be found it just requires a ~million digits :)

If you only want the bottom 10 digits and only adding and multiplying

^x is like multiplying x times

you only care about the last 10 digits of any number you are using
temporary or otherwise

Some of you may not know why due to multiplication being taught
wrongly at school. It is easy enough for anyone
to do a 99-digit by 99-digit multiplication only writing down the
answer ;)

This is done the way that a computer can be used to find the exact answer

consider

12345678
x30978793

the answer can be found a digit at a time:

if you reverse one of the numbers
30978793 -> 39787903

then the last digit of the answer is:

12345678
|
39787903

is the last digit of 8 * 3 = 24

tetron 22 Junior Poster

Random numbers need to use srand( ) otherwise you get the same
number each time

there are a few posts on this and a quick search will show you
some demo code
you should get the system time
and call
srand(time);

tetron 22 Junior Poster

It's difficult for me to explain, I'll try to, but perhaps someone else can explain better.

ditto :)

When you say: int x; or alpha my_alpha The computer has to create the space in memory that it needs to
store all of the information about the variable.
So for int x the computer allocates space for an int in memory
and points something to it that you are calling x.

now when you say

int x = 4;

in effect an x is created with an unknown value using x() in it
then this value is set to 4

where as

int x(3);

creates x but this time with 3 set immediately as if there is
x(int val) constructor

When you use the : You can call the constructors of other classes before the computer has finished creating the class
when it reaches the first { all of the memory has to be stored

so in your code it is as if you are saying:

gamma(int a, int b, float c)
:alpha(a * 2), u(a), [B]beta()[/B]
{
//all variables need to be created with defaults by here
gamma(c, c);
//you can then set specific values in here too
}

this implicit beta() constructor does not exist as you did not define it
and beta(float a, float b) cannot be used as the computer has no values for the floats

tetron 22 Junior Poster

I suppose you mean Visual Studio instead of 'visio', right?
Then again, Visual Studio comes with a batch file vcvarsall.bat

Thanks this was enough of a pointer for me to finish solving the problem. I bet there is a cleaner solution but this works:

1: Edit makefile
so that the paths for cl.exe & rc.exe can be found
have to put quotes ("") round as there needs to be spaces

Environment variables would probably work too but I cannot edit them here (My Computer-> Properties->Advanced)

2: Had to edit .rc as #include path was not being found so made it
full path

3: call vsvars32.bat from where makefile is! :)

4: call nmake

steps 3 & 4 need to use "" to work in dos prompt there are lots of misleading error messages to get to this stage

1 this is a capital letter Macro
i.e.

VISIO = "C:/Program Files/Microsoft Visual Studio 8/VC/bin"
#then instead of cl you write $(VISIO)/cl
tetron 22 Junior Poster

I think that my problems are just based upon things not being in the
right place.

I gave an explicit include path to the winver.h from where i go the
nmake.

This changed the error to:
U1077 '.\cl.EXE' return code 0x000135

this seems like a very general error and I am not sure what it is doing:
I think this is the makefile line that is failing

$(BIND)\detoured.dll: detoured.cpp detoured.res
	cl /LD $(CFLAGS) /Fe$@ /Fd$(BIND)\detoured.pdb detoured.cpp \
/link $(LINKFLAGS) /base:0xf000000 /incremental:no /subsystem:console \
/entry:DllMain /implib:$(LIBD)\detoured.lib \
/export:Detoured kernel32.lib detoured.res

Does this still mean that a file or dll is not being found

Where can I find a good article about writing makefiles?

tetron 22 Junior Poster

Hi I have what at first seemed to be a very simpe problem:

I have a Microsoft Package that requires me to use nmake to make a lib file. I am unfamiliar with make files as I use visio and XP.

Now I had to move somethings due to restricted write access on
the computer I am currently at

I have a Makefile in:
My documents/Folder/src/

I tried to move the entire visio contents:
/VC/bin/
to the same folder

then calling nmake from a command prompt I get
fatal error RC1015 cannot include file "winver.h"
from when rc is called

Now should I just edit the files to give explicit locations
or is there a better way?

I only need to run this code once so any hack will do?

tetron 22 Junior Poster

Wow yeah that fixed it. Thanks, now I need to figure out why that works.

I am probably missing something but your while loop on line 17

is this the logic you want?

if you hold at say 70 and the computer rolls a 1
doesn't that mean that you have a total human score of 70 and the computer total is 0 and that you should win.

But the while loop won't exit.

also
line 74:
while()
with a single return and no way to change the exit condition
is a bad choice of block
should be if()

tetron 22 Junior Poster

Even if you call the system time to do it every 30 minutes
requires a trigger device and as such requires some method
of checking when the time changes.

If you have an external program that sends a message this will still
in effect be slowing down the running of the function.

What is it that you are doing that is running true and wants to do
something every 30 minutes ?
what are you trying to do with function2() ?

You can add a counter in ints with only a minimal overhead

//in the while
if(--counter < 0)
{
//get system time if elapsed time > 30 mins start function2();
counter = counter_start;
}

I need simple timer that should not mess with the threads,and doesnt use Sleep().


And success of function2() must not affect running the function1.

Needs more explanation of function2() to know whether it should be function2() doing the timing.

tetron 22 Junior Poster

Assuming that in all your own .h you have #pragma once

If you rename _objects_ to _abcdefgh_1234
do you get the same error with "_objects_"
replaced with _abcdefgh_1234 ?

if not then you have two places where you have used the same function name and this needs to be fixed it could be var:: is used elsewhere

I always uses classes and don't use the using so as not to confuse
visio intellisense or risk polluting the namespace

I am not familiar with the SDL libraries that you are using
but I assume that you are trying to get some game to work
without using the windows api.

It might be missing something obvious... but there is a lot of
includes and code that are not being shown here and an equivalent
code for me does not give an error

works , but .... even with "#pragma once" on top Im getting

...
In function main
multiple definition of `var::_objects_
first defined here
In function main
multiple definition of var::_img_
first defined here
In function main
multiple definition of var::_font_
first defined here
In function main
multiple definition of var::_sound_
first defined here
In function main
first defined here|
In function main
multiple definition of var::quit
first defined here
In function main
multiple definition of var::pause
first defined here
...

obejcts.h

#pragma once

#ifndef OBJECTS_H_INCLUDED
#define OBJECTS_H_INCLUDED


....

using namespace std;

class game_object
....

class cpong1 : public …
tetron 22 Junior Poster

What is it that you want the system to do when

#tiered test
a 005 b 04
a  5 b 3
a 0005 b 5
#no spaces between number and letter
y 000a 
y 00091
#spaces
b 5  abc
b  5 abcd
b   5 abc

?
As I am about to have to do a fully optimised retrieval of words I thought I'd see how close my solution was as I am rusty having put a wrapper around all my sort algorithms ages ago.

But to save me writing about another 4 solutions that I am sure someone here will beat :) is it just treating numbers separated by spaces as a whole number then sub sorting on the format?

thanks

tetron 22 Junior Poster

here i wanted to just put the added value in the suggested variable like above x and y from the main()..
when i tried to do it in the main() , i dunno but where it picked the garbage value..
becoz i think the function >>i checked it using debugging and it worked perfectly....can u just tell me from where it was picking the garbage value???

with i and r being private
does
a.r compile for A()
you need accessors or public varibales

I suspect that your output is if you compile
"0+0i"
ok there are two errors in your code both occurring at the same place when you call the A() function

your set function should be working fine.

1- if you look at what jonsca says it will fix your problem
when you put re and im into the function
the function creates two new variables
as if it says
double re2 = re;
double im2 = im;
and in your function you are changing re2 & im2

to change the value is as jonsca says you need a reference
look at the & he has added! try it

2 - this mistake won't stop you function from working but if you do
c = a + b;
or
a += b;
should really be how you perform an addition
so either update

sleepybug commented: precisely,just what i needed.thanks a lot man! +0
tetron 22 Junior Poster

At first glance is a float enough precision for the accuracy you need?
Do you need double unless you are seing a separate number 15
I suspect that the file is being chopped as you want but you need a double.

If these are being stored from floats to be reloaded you can use a binary file instead of ascii.

I I am using the following code to read

I get 1970326 instead of 19700326.15
Somehow, the decimals at the end are being truncated!!
This only happens to the first column of data, the other columns are read okay!

Further, sometimes, a number like 19840907 in input file will changed to 19840908 in the vector and this seems to happen randomly.

Can anybody tell me what the heck is going on? This is driving me insane.

tetron 22 Junior Poster

oh, the little cout's here and there were just me debugging... just to see where things were hanging up at..

Why not build a tree class something like:

#include <vector>

class tree
{
public:
tree();
tree (*parent);

add_child(tree * new_child);
set_parent(tree * parent);
tree * get_parent();
std::vector<tree *> get_children();
clear();

private:
tree * my_parent;
std::vector<tree *> my_children;

};

tree::tree()
: my_parent(NULL):
{
}

add_child(tree * new_child)
{
new_child->set_parent(this);
tree.push_back(new_child);
}

This is an incomplete example
as there is no depth

If this is just a small tree I would recommend
bool has_parent();
int calculate_depth(); //requires iteration or recursion

the alternative would require updating all of the childs' child nodes
when adding

tetron 22 Junior Poster

main should always return an int, not be void.

Why? It compiles to valid code, The extra return 0 is just more code to maintain.

SLEEPYBUG:
There are some general things that help when writing code
and it is best to start early:

give your functions meaningful names
A(); says little about your intention add() would be a better name.
Complex C;
is this intended just as a temporary variable fine
but it is not needed
x = a.r + r;
y = a.i + i;
will work with the references.
My concern is that you were intending to return C;
and have not done it. Did you intend this?

Complex Add(Complex a, double dr, double di);
Complex Add(Complex a, Complex b);

otherwise the reference will be fine but what is it you are wanting
the function to do ?
you might want a display() function for instance

tetron 22 Junior Poster

You can make your code more readable by

if(c >= 'a' && c <= 'z')
{
//lower case
}
else if(c >= 'A' && c <= 'Z'
{
}

You can also do things like
char diff('A');
diff -= 'a';

to get the 32 number

tetron 22 Junior Poster

I am using a different version of compiler so different errors but
have you scoped vector?
the std::

//var.h
#pragma once
#include <vector>
namespace var
{
std::vector<int *> vpi;
std::vector<double *> vdi
}

works for me.

tetron 22 Junior Poster

I wrote a program to compare two text files character by character and its not working probably an easy thing im just not seeing.

for( int i = 0; !ifs2.eof(); i++ ){
    getline( ifs2, s2 );

    if( !ifs1.eof() ){
      getline( ifs1, s1 );

      c1 = s1[i];
      c2 = s2[i];
      if( c1 != c2 )
        cout << endl << "Files differ at line" << (i + 1) << endl;
    }
  }

your line

c1 = s1

i is stepping for lines but you are only cheking the index every
i chars

you do not iterate across line so only are checking a diagonla of cahrs

tetron 22 Junior Poster

Assuming that your code was showing multiple files
including the same file indirectly

by adding the preprocessor line to the top of all of your .h files

#pragma once

you can ensure that no single file includes the same file twice.

tetron 22 Junior Poster

Well I did ask :) , I had to look-up a lot of the scientific terms and even then some areas are still very complicated.

So you have a statistical model of objects rotating ~in a plane towards a centre so that
the system becomes viscous and slows down.

My concern is that you have a particle that has mass, yet the properties that
are being stored are not representative of a particle object but would be an orbit object.
with code like this it is essential to know what represents meaningful elements to your
calculation.

Fully optimised code will not be suitable for another purpose, but minimal overhead is only going
to be a few seconds to allow code to object orientatede and re-usable. There has to be an awareness
that your time in writing, error proofing and maintaining the code can be the most time critical issue.

Now you can iterate over arrays quickly as a[1000] has a pointer 'a' but it can get tricky
to read what exactly you are doing at each step.
It is often beneficial to take advantage of existing solutions and there will be a lot of common tasks
this makes the use of vectors preferable in my opinion.

With vectors they are built for speed so can overflow if you misuse them.
But what you can easily do with vectors is have a test problem with fewer …

tetron 22 Junior Poster

Hi all,

I am just getting into the world of OOP and I'm not totally sure in what situations it's better to use objects and when it's simpler to just revert to arrays.

For scientific code it is normally best to ensure that the code is clearly readable, and reusability is less important than most OOP, but it useful to have both at all times

The first thing you need to do is be sure of what you need for each particle:
mass
position (this might be a coord xyz for a local origin)
speed (coord xyz)
spin
volume

The you might need a time frame handled seperately
update each coordinate check for collisions then decide whether
a particle breaks-up sticks to another particle bounces.

It is important to get the system working before optimisation

Arrays have a short shelf life and can introduce magic numbers if
you have an array of X values and Y values what happens if you miss one on input?

what you can use is a std::vector<particles>
this is #include <vector>

then if you can iterate over the vector in a for loop
getting the particle speeds have
if you put this in a class with methods

add_particle(particle &p);
update_particles();
change_particle(particle & p, int new_state);
advance_time();
you can control the methods:

but if you can be clearer over the design the problem …

tetron 22 Junior Poster

Minimum memory and speed is always a while(--size)

This will stop when size is 0 and so size should been used first as a do while if using same size as original array it wouldn't add the last number :)
but in real life I don't use do while and would have used a for loop and iterators and stl, this is why it is important to write clear code ;)

tetron 22 Junior Poster

Minimum memory and speed is always a compromise

log10 is an ugly way of solving this with possibly fewer steps unfortunately math.h only has double and float versions so

#include <math.h>

while(--size)
{
++Counts[ int( log10( float(*num) ) ) ];
++num;
}

This code uses fewer temp variables if you use log10 as a look-up and though logss requires more space this would not count as an overhead. where "0" is being counted as 1 digit

But clearly the code is insane to read and temp variables would be
best contained within a function

so

//assuming only doing this for one array of numbers
while(--size)
{
++Counts[digits(*num)];
++num;
}

This has removed all error checking that digits is in range of counts
for the purpose of speed it is assumed that num has checked this.

now
you can use NARUE's sensible function or the ugly

inline int digits(int value)
{
float val(value);
float ret = log10(val); //math.h pollutes the namespace
return int(ret); 
}

and by being separate you can chose how to optimise it later

the *num is because all arrays act as pointers and is faster than [] which is random access but it has been superceded by the stl

the ++x is supposedly better than x++ as x++ uses a temp but
if you time it I doubt your compiler does what you tell it and will do the same for both.

The penalty …

tetron 22 Junior Poster

O
And what the heck does tetron's first post have to do with anything in this thread?

Sorry, I did misread the question a bit as regards "string literal" :$

But looking at the original code I don't think the asker has figured out find() so the question of parsing lines to find the string
/* " */ std::string("hello//world\n\tgoodbye");
is not the point of the exercise I think there are a lot of parts of the
code that are pasted in without understanding.

tetron 22 Junior Poster

This looks at lot like a template code that someone is asking you to modify without you having understood the parts.

I am not quite sure why you would want to output a double quote in real life as it is not a useful piece of information

but you want to show something

std::string str = "tetron";
cout << str;

This will output the word tetron
but you really want to add in an extra line and tell it to print at the
same time so you should use a special cout variable called endl;

There are a couple of points with the original code I am surprised
by there is a c-style main declaration reading in argv[] when you
don't need parameters and if you use endl; you can get rid of system.(pause);

#include <string> //words and sentences
#include <iosmtream> //cout & cin

void main()
{
//set the value of line as you initialise it
std::string line("I answered, \"no.\"  Now the nest sentence.");
char to_find = '"';
//we want a special int to avoid awarning but just like int pos;
std::string::size_type number_of_letter_in_line(0), pos(0); 

//you can cout a " by using << with to find
std::cout << to_find << std::endl;

//find() starts looking at a letter_number you give it 
line.find(to_find, pos); //starts looking at I
std::cout << "found " << to_find << " at " << pos << std::endl;
 //this will give you 0 if found which is wrong
pos = …
tetron 22 Junior Poster

This is a question about tolerance of accuracy and it does depend on the application that you are using as a rough

rule of thumb I use the 0.000001; if I am looking for a stop condition
but you can go smaller if you
have the ratios
Consider:
(a*d == c*b) easier to establish the range of error

but the answer depends on the problem you are dealing with.

it is unusual to be comparing ratios normally you are comparing to 0
if you are looking
The matissa and the exponent
there are 32 bits for each available and it is the scale of the numbers that can be questionable if the numbers are the same order of magnitude then a single calculation the error will be very small.
10^356 - 0.999999999999*10^356
still gives an error of 10^344
so a tolerance will be normally
(a - b )/ b
so the error mainly comes from the mantissa not being enough digits
which if checking for 0 is probably 31 bits accurate for a single calculation so the ratio fo errors is about 1 / 2 000 000 000

Without a precise application this cannot be quantified I have had a problem using floats often but doubles extremely rarely.

Most errors come from the interpretation of non-base 2 numbers in the wrong format so that

float f(10000.0);
should be
float f(10000.0f);

tetron 22 Junior Poster

if you are using c++
there are useful containers in the stl standard template library

if you read up about strings you will find that a lot of the work has been done for you but beware replace() doesn't do what you would expect

//pseudo code to put buffer in string

#include <string>
std::string str;
//copy buffer into 
str.assign(pointer_to_buffer, buffer_size);

once you have a string there are functions that you can call to do
the common things you want find(), replace()

you need to find a method for finding your location

and something that looks messy is needed but is actually simple

like an int there is a type called size_type this is just an int without negative values.
so
std::string::size_type pos(0);
is just a number pointing to 0
to check if a string has been found

std::string to_find("9000"); 
pos = find(to_find, pos);
if(pos != std::string npos)
{
//we have found it starting at: pos
//so now you need to find the end and store it
}

.size() tells you howmany chars are in the string
so
to_find.size() //will return 4
so you can find the end of the string

finally replace will let the 9000 be changed to what ever you like
and in the long run this is how you will learn to do this and there are fewer errors to be made.


hi all....i have small …

tetron 22 Junior Poster

I chopped the big file into smaller chunks and all is working ok. The file was alright it was a problem with memory and new() but with the smaller files everything was fine.

tetron 22 Junior Poster

I cannot test any script at the moment as I am in the middle of a long run and looking for thngs to do before it finishes.

The ascii charcter charts show that 130 should be
é so the char(130) is working
the -126

a char is 8 bits and like ints it is possible to treat them as signed numbers so as 256 - 126 = 130
the int to char conversion is not treating the char as a character but as a signed number
char c = 'é';
unsigned int(c);
should be 130
not sure which compiler option has caused this.

but it helps if you output the char next to the number to check that
everything is what you think it is in your code
"/n"
should be replaced by endl; this can be important for later examples.

cout << ">" << i << "< >" <<temp <<endl;
as for the -23 this doesn't look right where are you getting the é
if you copy and paste from word it may be a different symbol to what you think it is! and so it wraps around the 256 possibilities are only one of two bytes it uses.

When you use char(130) you get the é. When you do int('é') you get -23... and with my program to get value it is -126...

How on earth can I get the 130 value …

tetron 22 Junior Poster

My only problem is the spacing..... to make it right.... i need to make it inverted pyramid pattern...
like this:
this is my code and only thing that wrong is the spacing before the rows...

If I have understood you correctly you have an unwanted space at
the start of each line and that comes from your for loop.

#include <iostream.h>
#include <string.h>
#include <conio.h>
main()
{
clrscr();
	int num,n;
	cout<<"enter:";
	cin>>n;
	num=0;
	while (num !=n)
	{
	 for(int i = n; i >  num;--i)
		 {
		cout << " " << i;

You are outputting the first space here
if you:

//although cout << i << " "; should work
cout << i;
if(i != num + 1)
{
cout << " ";
}

other spaces might want adjusting too

tetron 22 Junior Poster

2 approaches to consider:

1st assuming that you have a list of questions that are unique
in something like a std::vector<std::string> questions

there are two approaches I would recommend #2

#1
Shuffle the questions so that they are in a random order
You can use a method suggest by the other posters

have an iterator (something to point to the contents)
point to the [0] string of the shuffled questions
std::string<std::vector>::iterator it(questions.begin());

on get_question you can get current_string
*it (to get the value the iterator is pointing to) in this case a string
++it; //move onto next

need to check (it != questions.end())
as this would mean you have run out of questions

#2
leave the questions fixed in order

have an index of ints

int number_of_questions = questions.size();
std::vector<int> index;
for(int i = 0; i < number_of_questions; ++i)
{
index.push_back(i);
}

Now you can shuffle the index to give a shuffled index
then when you want a question get the number

//when a new asker arrives
index = shuffle(index);
std::vector<int> shuffled_index = index;

int ind = 0;
//now each time when you get a question
//check ind ok
if(ind >=0 && ind < shuffled_index.size())
{
int cur_ind = shuffled_index[ind];
//use current ind to get the question
if(cur_ind >= 0 && cur_ind < questions.size())
{
std::string question = questions[cur_ind];
}
//get the next random id
++ind
}
else
{ …
tetron 22 Junior Poster

Since you are trying to allocate rather huge amounts of memory (2GB), I'd guess that the limitations are more probably imposed by your operating system (which one is it?) than the std::string implementation.

See MSDN documentation on Memory and Address Space Limits. Are you perhaps reaching the 2GB user-mode virtual address space limit there?

PS. As already suggested, perhaps process the file in much much smaller chunks than what you are now planning.

Thanks everyone for your input,

As I am using XP there is a 4Gb physical memory limit and
I suspect this is restricting the application to ~2GB max.

I was completely unaware that this limit existed as most windows classes
appear to have been built with longs I figured since memory address registers
are dealing 100GB that this issue wasn't applicaible

I am concerned that like the millenium bug there is a lot
of microsoft code that won't cope beyond the 4GB limit despite claims
such as ie 8 downloads :(

Here was a work around not involving a new file:

try
{
 file.seekg (0, std::ios::beg);
 std::string data;
 for(int i(0); i < 16; ++i)
 {
  size = 64 * 1024 * 1024;
  char * smaller_memblock = new char [size];
  file.read(smaller_memblock, size);
  if(size < file.gcount())
  {
    size = file.gcount();
  }
  data.append(memblock, size);
  std::cout << data.size() << "<>" << size << std::endl;
  delete [] smaller_memblock;
}

interestingly this doesn't allow for a std::string above 640Mb
although …

tetron 22 Junior Poster

I suspect that this kind of question is just homework so perhaps I should not be answering it.

Binary = base 2
there is a function that will tell you the remainder of any number
called modulo and use the % sign

so 5%3 = 2;
as an integer representation of a binary to get the last digit
int binary_digit = i%2
to get the next digit you can divide
i = i/2; or i /= 2;
before doing this iteratively
you should check that i > 2
if not you want to
stop.


Greetings everyone! I hope to learn and become better in programming. But honestly, my heart fails me everytime I face a new assignment. This one is just another heartache.

Thing is, the question wants me to print out n-bit strings in lexicographical order ( meaning increasing order ). And I must use recursion. I am new to this concept let alone c++. I hope you can guide me here.

Recursion means calling the function from within itself and though this isn't appropriate for the current task it is a teaching assignment.

so you call the function from within in the function as you are doing
but be careful if you get it wrong it will never stop!

void GetBinaryString(int &i, std::string &binary_as_a _string)
{
    //need to add latest bit to binary_as_a_string
    char digit('0');
    if(i%2 == 1)
    { 
       //need …
tetron 22 Junior Poster

How would I make or find a spellcheck for wordpad and I don't mean like all spellchecker I mean like a built in spellcheck like in word were you just press F7 and bam no haveing a whole other program up so how would I even start to make that?

I don't have the complete answer to the question, but there are some resources that might be worth looking at but it will not be an instant fix.

1. find a list of words
2. index the words for fast look-ups
3. combine this into rich text box application

In short it would be faster to find one that already exists such as word.

First how to add a spellchecker. You first need a list of all valid spellings to have in a large file. A partial fix for this would be something like WordNet although it only contains verbs, nouns, adjectives and adverbs.

Then once a user enters a character into a rich text field such as wordpad you need to detect if it is a non-letter. If it is a non-letter you need to find the word in the dictionary.
You can do this with a keyboard event listener for OnKeydown();

The next step is getting a Richtext box application There is too much required to give all of the details here but these are some of the starting points to consider.

If you have a full or student …

tetron 22 Junior Poster

the opening of the file is in another function that calls that function~
and I dont think using the array will be convenient because the words will consume too much memory..

For 50 words as described memory should not be even close to being an issue I have a code that loads WordNet every time it runs which is 500, 000 words ~ 30 seconds including look-ups and indexing.

If you load the words into a container from a file. You can edit the
file and just get the words you want. How often will you be loading the file not very it is unlikely that the number of words that you are talking about would even register in time.

so if you can control or know the format of the file you just edit the file and the program will load no problem.

if you use a vector it does not matter how many words are in your array the random number can take the vector .size()

#include <vector>
#include <string>
#include <fstream>

std::vector<std::string> words;
//load the words once 
std::ifstream word_file("word_file.txt");
/*
now you can get line until word size == 0
*/
/*this code I can see is  above so I will abreviate
if(fin.open())
{
int count(0), max_count(10000); //limit to 10000 words
while(count < max_count)
{
std::string word = fin.get_line();
if(word.size() == 0)
{
//empty line so end of words
break;
}
else
{
//add word to the list
words.push_back(word);
}
++count; …
tetron 22 Junior Poster

I am having problems with the new operator() specifically within
std::string

I appear to have hit a memory limit in visual studio.

Ideally I would like someone to help me find one of the following solutions:

1 - Can I access the memory in a very big file directly without a memory buffer?
2 - How do you increase the maximum size of the free store in visual studio?

My approach at the moment is not working I have a very big file that I want to
chop before processing.

- I create a membuffer for a 1Gb file (this was made from 25Gb file)
- then try to use a std::string to iterate over the string.

but I cannnot create the string as I get
bad allocation error
from cstr()

A simplified version of my code

#include <string>
#include <exception>
#include <fstream>
#include <iostream>

void main()
{

 std::ifstream fin("D:\\Gig1.txt", std::ios::in);
 if(fin.is_open)
 {
  unsigned int sz(1073741825); // 1 gig (1024)^3
  char * memblock = new char[sz]; //this is fine
  //check file sz is right size not called as sz == gcount
  fin.seekg(0, std::ios::beg);
  fin.read(memblock, sz);
  if(sz > fin.gcount())
  {
    sz = fin.gcount();
  }

  try
  {
	std::string str(memblock, sz); //too much for visio :(
  }
  catch(exception &e)
  {
   std::cout << e.what() << std::endl;
  }

  delete [] memblock;
  fin.close();
 }


}

This is an approximate code and I am posting here as my first post was asking the …

tetron 22 Junior Poster

I have discovered that the issue I have is that I am trying to use too much memory and the new() operator is throwing in the string
as I am overflowing the visio limit.

So I was really asking the wrong question, so I will have to try a slightly different approach.

It appears that I am creating a temp structure that causes an overflow and I shouldn't really need this.

tetron 22 Junior Poster

Thanks for your help.

Sorry, I did not make myself clear the comment was supposed to indicate that I had tried using ifstream with in as well.

I'm not sure why you are using a binary fstream to read text data.

The problem that I have is that I do not understand why the string cstr() might be failing. The only thing that I am not sure about is the state ot the original file as I used a brute force approach to chop the 25Gbytes

I don't know stat() and could not find much documentation on it. A c struct for getting file info? I looked at sys/stat.h and I think that it still uses an int_32 so would be unusable with the original 25Gig file.

4. If you want to parse a character at a time, use get()

This might be usable but I am not sure what happens around the 4Gig mark. When I said find the chars directly I meant char * pc; equivalent but even char * this won't cope with the file as not big enough.

tetron 22 Junior Poster

I have not directly had to change over from c to c++ for a large number of files but there are couple of things to perhaps clarify in your questions.

I think that what you have is effectively a file called "functions.h"
In a functions.c file you have defined several functions:
fun1()
fun2()
...

and what you are trying to do is change the definitions and inner workings of the function but not what the function is doing.

IF you are using a function in lots of places it is safe to assume that the current version of the function performs the task as you want it to. Therefore, it can be used to test that your new c++ version is still working properly. Most C code should run within c++so the old c code can be used as a starting point.

You can either have a version of each include file in a c++ folder and you can keep the name of the file but you temporarily
#include "c++/function.h"
that can be changed to function when all of the files have been converted and then change the folder properties. This works if you can change all of the class in one go.

method 2
If you place all of c++ code into a namespace then you can have
functions with the same name and when you call the c++ version
it can be scoped name::fun1();

tetron 22 Junior Poster

I will try to post exact code tomorrow if wanted when I am at the correct computer but for now I thought I ought to give a quick clarification.

In brief the code is roughly

#include <fstream>
#include <string>
#include <iostream>
void main()
{
unsigned int size(1073741824); //orig pos_type
char * memblock = new[size];

std::string file_name("D:\\wiki.txt"); 
/* a file that is the memblock read written for 1st gig
and the ofstream write */
//read in 1 Gig file
std::ifstream fin(file_name.c_str(),std::ios::binary); // also used in

if(fin.is_open())
{

   fin.seekg (0, std::ios::beg);
   fin.read (memblock, size);
//check how much has been read;
   if(size > fin.gcount())
   {
     size = fin.gcount();
   }
  std::string dummy("");
  std::cout <<dummy.max_size() <<"<>" << size << std::endl;
  std::string data(memblock, size); //<-<< this goes wrong
  std::cout << "I Don't get here! for big file" << std::endl;
 fin.close();
}
//clean up memory
delete [] memblock;
}

works for test file but not for big file
where it outputs max size as expected:
4294967296<>1073741824
Then visio crashes on the constructor

2. Why don't you use an XML library to parse the code. There are hundreds of XML libraries out there. Such libraries can save you a ton of work and they are usually very efficient.

3. Why are you trying to read the entire file at once? Couldn't you process line by line, and not have to worry about overflows at all
?

The original file that I want to process is 25Gb this presents problems for a very …

tetron 22 Junior Poster

I have a
std::string (char *, std::string::size_t )
constructor failing and I am not sure why.

For my small test file there was no problem, but when using
ifstream::read()
with an unsigned int sz of 1Gb (1073741824)
(I think that I used a pos_type 1st time)
and the resulting char* memblock

I first compare against gcount to confirm that sz isnt bigger.

Have I got an overflow problem max_size() returns 4Gb as expected?

Or is it a problem with the file data?

The main problem that I have is that I am trying to chop a very big file (25Gb) xml into manageable chunks. So I loaded the file in 1Gb
chunks and wrote them straight out using ifstream read() and ofstream write(). So my files might not be in the state that I think they are and might be missing an end of file.

I made a small 260k file in the same way that works fine.

Can I access the file to chop it on html tags in Windows XP.

Thanks,

David

P.S. the 25Gb is wikipedia text only