subith86 17 Junior Poster

I am planning to write an application in windows which will temporarily block the configured websites irrespective of what browser I am using. As I am completely a newbie in this I want to know where to start. Please provide me with any useful links which can help me. If you know any similar opensource program, please share it with me so that I can get an idea of what to do.

subith86 17 Junior Poster

This link explains better

subith86 17 Junior Poster

I have a code which gives the maximum value I can get by filling the knapsack with the optimal set of weights.

int arr[5] = {0, 0, 0, 0, 0};
int Weight[5] = {2, 5, 8, 7, 9};
int Value[5]  = {4, 5, 7, 9, 8};
const int n = 5;
const int maxCapacity = 20;

int maximum(int a, int b)
{
    return a > b ? a : b;
}

int knapsack(int capacity, int i)
{
    if (i > n-1) return 0;

    if (capacity < Weight[i])
    {
        return knapsack(capacity, i+1);
    }
    else
    {
        return maximum (knapsack(capacity, i+1),
                        knapsack(capacity - Weight[i], i+1) + Value[i]);
    }
}

int main (void)
{
    cout<<knapsack(maxCapacity,0)<<endl;
    return 0;
}

I need to extend this solution by printing which all weights are used to find the optimal solution. For this I plan to use an array arr initialized to 0. Whenever a weight is used I mark the corresponding position in arr by 1, otherwise it remains 0.

First thing that came into my mind is to change the maximum() function like shown below

int maximum(int a, int b, int i)
{
    if (a > b)
    {
        if (arr[i] == 1) arr[i] = 0;
        return a;
    }
    else
    {
        if (arr[i] == 0) arr[i] = 1;
        return b;
    }
}

But even this solution fails for some combination of weights and values. For illustration purpose, I have hard coded the values which fail. Any suggestions on how to go forward?

PS: This …

subith86 17 Junior Poster
if (0 > spendMinute)
{
    spendMinute = 60 + spendMinute;
    spendHours-- ;
}

Add this piece of code at line 15. It will work

subith86 17 Junior Poster

cin >> Point::m_Xcoord >> Point::m_Ycoord;

I didn't take the effort to understand what you are trying to do but there is definitely an error at line 38.
You cannot access structure member variables using :: operator unless they are static. You need to create an instance of structure to access it. Or you have to make the members static.

1.

    struct Point
    {
        float m_Xcoord;
        float m_Ycoord;

    };

    int main ()
    {
        Point instance; //create an instance
        cin >> instance.m_Xcoord >> instance.m_Ycoord; //access using instance
    }

OR

2.

    struct Point
    {
        static float m_Xcoord; //make it static
        static float m_Ycoord; //make it static

    };

    int main()
    {
        cin >> Point::m_Xcoord >> Point::m_Ycoord;
    }
subith86 17 Junior Poster

Boost library is one option. But given that you are a beginner, and you want to go the hard way by using less complex C++ concepts, then think and note down how you will do this task if you were asked to do it manually.

  1. take the given day, month, year. (It can be stored in a structure, if you have learned it already)
  2. take system day, month, year. (structure as above)
  3. Modify given date by adding x to the given day so that it matches system day. Leap years to be taken into account.
  4. Modify given date by adding y to the given month so that it matches system month. Count number of days in this gap (30+31+31+30+31....). Lets call it y_days. Leap years to be taken into account.
  5. add z to the given year so that it matches system year. Count the number of days in this gap. Lets call it z_days. z_days = z * 365.
  6. count the number of leap years between 2 years. let it be called ly.
  7. Number of days = x + y_days + z_days + ly

Now go ahead and implement :)

subith86 17 Junior Poster

It's already in string
int main ( int argc, char *argv[] )

subith86 17 Junior Poster

Yes, I will try with the latest compiler. Thanks for all of your suggestions.

subith86 17 Junior Poster

Anybody of you got any idea what this "internal compiler error: Segmentation fault" means?

I searched internet, but didn't get anything useful. Then I did my analysis. I found out something peculiar. The code that I am trying to compile is a file for unit testing one of our classes. It contains 880 test cases. All these 880 test cases are individual cases in a switch statement. When I comment out any of the 80 cases (in any order) and keep 800 or less cases in the switch statement, it compiles without giving the above error.

We use CPPUNIT frame work for unit testing.

Here is the complete output.

/<some_path>/MyClassTest.cpp: In static member function `static CppUnit::Test* MyClassTest::suite()':
/<some_path>/MyClassTest.cpp:11774: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <URL:http://bugzilla.redhat.com/bugzilla> for instructions.
Preprocessed source stored into /tmp/ccGCtrA5.out file, please attach this to your bugreport.
make[1]: *** [/<some_path>/MyClassTest.o] Error 1
make[1]: Leaving directory `/<some_path>/make'
make: *** [MyClassTest] Error 2
subith86 17 Junior Poster

Line 19 - 23 : Why can't you use a similar loop condition as used in line 3 - 7

subith86 17 Junior Poster

Dude, this has hundreds of errors when I compiled. Either you post a proper code or point out which line of code concerns you.

subith86 17 Junior Poster

Common mistake that everybody makes. :)
Line 21 : use "&" in scanf

Ancient Dragon commented: Good observation -- I missed that :) +17
subith86 17 Junior Poster

I seriously believe this is not the right way to code. Why can't you use arrays and make the code shorter? Or is it that you are not taught about arrays till now?

Mark as solved if you are done with it.

subith86 17 Junior Poster

In your code you are not calling isLeapYear()

//if (!isLeapYear) -- wrong
if (!isLeapYear(year)) //right way to call the function!!

Why I preferred unsigned is that there is not such thing like a negative date, month or year.

subith86 17 Junior Poster

oh come on!!!
I should not have spoon fed :(

1. There is no harm in using int variables. change unsigned to int.
2. += can be replaced with ordinal_day = ordinal_day + month;
3. Last but not least, you must have a bool function for leap year check. I didn't take the pain in writing one for you. So I put a comment inside if-condition. You have to call a bool function, inside the if-condition. The argument to that function should be the year and it returns true or false.

subith86 17 Junior Poster

Why can't you do something like this.

unsigned int mm; //holds the month
unsigned int dd; //holds the day
unsigned int yy; //holds the year

unsigned int ordinal_day = 0; //holds your ordinal day number

//define an array which holds the number of days in each month
unsigned int month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if (/* yy is leap year*/)
    month[1] = 29;

for (int i = 0; i < (mm-1) ; i++)
    ordinal_day += month[i];

ordinal_day += day;
subith86 17 Junior Poster

How, with the first method, would you expect to support something like a = b = c; ?

satisfying answer. thank you :)

subith86 17 Junior Poster

Hi,

I have overloaded assignment operator like below and it worked perfectly fine.

void Test::operator = (Test& obj)
{
    this->a = obj.a;
    this->b = obj.b;
}

But when I googled more about this, I could see all of the examples used a different prototype like this

Test& Test::operator = (Test& obj)
{
    //do something on *this
    return *this;
}

Is there anything wrong in the first method?

subith86 17 Junior Poster

what is your large number? which data type are you using to hold large numbers?

subith86 17 Junior Poster

why is there no enclosing brackets for the lines under for loop? Is it intentionally missed out? From the logic under for-loop, I don't think so

subith86 17 Junior Poster

Dude, you are giving us a 500 line code and asking us to find the bug. Why can't you debug a bit on your own and post only that code portion which is the reason for your "lock up"?

subith86 17 Junior Poster

A tricky way, may not be the best way. Here it is:

#include <iostream>

using namespace std;

int main()
{
    int a[2] = {1,5};
    long addr1 = (long)(&a[0]);
    long addr2 = (long)(&a[1]);
    cout<<(addr2 - addr1)<<endl;
    return 0;
}

take absolute value of addr2-addr1 inorder to avoid a negative answer.

subith86 17 Junior Poster

Ok, if you want to retrieve the info at the last use "back"

a_student.assignments.back()

If you want to retrieve from anywhere else using an index, use "at"

a_student.assignments.at(4)

See this link for more info

subith86 17 Junior Poster

The program can be greatly simplified

But the reason why he did this way is to output the count down. In fact, count up. Starts from 0:00 to 1:30

subith86 17 Junior Poster

at line 29 you are setting seconds back to 0. So it's an infinite loop.
Use a different variable in for loop condition.

subith86 17 Junior Poster

I didn't take the trouble in going through your entire code. But what sounds to me is that you have to use a static variable as ID. Initialize it to 1. increment it every time you add a patient.

subith86 17 Junior Poster

A side effect still happens at an unspecified moment somewhere prior to a sequence point.

I'm sorry to say I didn't understand this line. I also googled about undefined behavior and sequence point. I could find nowhere anybody mentioning about pre increment operator, though there are many posts which gives undefined behavior while using post increment. In the example that I gave,

i = 10;
i = ++i;
//step 1 : increment happens, i becomes 11.
//step 2 : i = 11; assignment is going to happen with 11.
//step 3 : value of i becomes 11 after assignment.

My question is, ++ operator already did its job in step 1. So what is the problem?

subith86 17 Junior Poster

ok. Thanks. So

i = i++;

is undefined because of two assignments happening
1. modification done using = operator.
2. modification done by ++ operator.

So if my understanding is correct this assignment should be okay and doesn't have undefined behavior.

i = ++i;

Am I right?

subith86 17 Junior Poster

Run away from that teacher as fast as you can.

y = 2*y++ + --x;

Correct me if I'm wrong. But how is this an undefined behavior? I agree that the below line will give undefined behavior.

x = y++ * --y;

Because we cannot predict which one (y++ or --y) will be evaluated first.
But In this case

y = 2*y++ + --x;

2*y++ and --x are independent. In whatever order they are executed, we get the same result. And only after the result is got, it will be assigned to y. I may be wrong here, but I would like to know what is the undefined behavior here.

subith86 17 Junior Poster

Hello, basically I want to return an array from a function (So I don't output things in the class - just main)

But I seem to get the error: "invalid types 'int[int]' for array subscript"

Here is the code:

#include <iostream>

using namespace std;

int matrix()
{
	int matrix[10] = 
	{
		1, 1, 1, 1, 1,	
		1, 1, 1, 1, 1	
	};
	
	return *matrix;
	
}
int main(int argc, char *argv[]) {
	
	int matr = matrix();	

	for(int i=0; (i < 10); i++)
	{
		cout << matr[i] << "\t";		
	}
}

Any help would be great :)

Your code will compile if some changes are made in line 5, 13, 19 as shown below

#include <iostream>

using namespace std;

int* matrix()
{
        int matrix[10] =
        {
                1, 1, 1, 1, 1,
                1, 1, 1, 1, 1
        };

        return matrix;

}

int main(int argc, char *argv[]) {

        int* matr = matrix();

        for(int i=0; (i < 10); i++)
        {
                cout << matr[i] << "\t";
        }
}

But this is NEVER recommended and there are high chances it might not work. Why? Because the array is defined inside matrix(). So array will reside in the stack area of matrix(). When matrix() goes out of scope (after return to main function) the memory block where the array elements are stored maybe overwritten and hence data loss.

So when you want to return an array from a function either use the static way as suggested by thines01. Or you have to store the array in heap. …

subith86 17 Junior Poster

try this :)

while(std::cin >> numberinput){
    //std::cin >> numberinput;
    LinkedList.InsertFront(numberinput);
}
subith86 17 Junior Poster

Yes it is, but not the way I want.
The output is different

It's pretty simple. You are not looping fully while printing. Make this change in line 40 - 43 (extra line added) and it will work.

for( i=0; i<c ; i++) {
    printf("%c", line[i]);
}
printf("%c", line[i]);
subith86 17 Junior Poster

use vector::assign
See this link. There is a similar example given.

subith86 17 Junior Poster

but it's all an agreement that you make with your code.

Yes, exactly. That is all that you can do.

What I meant is, it is not possible to remove any element from an array. If it is the elements at the end, we can somehow reduce the length variable, so that it doesn't iterate beyond that. But what if you want to delete the elements in the middle? So in short, once memory is allocated for a static array, it cannot be altered. Only thing that you can do is to change the value contained in it. Usually what I have seen in many programs is the use of -1. But it is limited in a case where your array is supposed to hold negative values.

subith86 17 Junior Poster

The easiest way is just to set it to NULL.

How is that possible? If you set it to NULL, the value will still be there and it is zero.

int a[5] = {1,2,3,4,5};
        printf("%d", sizeof(a));//prints 20 as the size
        a[4] = NULL;
        printf("%d", sizeof(a));//prints 20 again

It is never possible to increase or decrease the size of a static array. Same is the case with adding/deleting elements to/from a static array.

subith86 17 Junior Poster

Are you asking what templates are? Or what is the job of template in your code? If you don't know what templates are, before trying to understand this code, you need to learn about templates. Take a good book or take some online material about templates and learn.

I will brief about template functions here

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

Here we have a GetMax function which accepts two arguments, both of type T and returns T type. The functionality inside this function is generic for all data types. Why a template is used is because you don't need to repeat the code for each and every data type like int, double, char etc.
But you have to note that the duplication is avoided only in the source code. When this code is compiled, the compiler generates separate versions of this function for separate data types, by replacing the T with int or double or char or any other. Now, how many versions of this function is to be generated? It is determined by the number of function calls to the template function. Suppose the following lines are there in your code

GetMax(4, 7);
GetMax(3.45, 8.10);
GetMax(8.121, -902.12);

Here two versions of the GetMax will be generated.

int GetMax(int, int);
double GetMax(double, double);

This was just a brief overview. There are more to read about templates. Also, go through …

subith86 17 Junior Poster

1. Write a c++ program that generates the following series: 0 -1 4 -9 16 -25 36 -49 64 -81 100

and also this one
- Nell

Break it into two series
0 4 16 36 64 100 (square of even numbers starting from zero)
-1 -9 -25 -49 -81 (negative of square of odd numbers)
Mix both and you get the result

2. write a program that generates the fibonacci series: 1 1 2 3 5 8 13 up to 50th term.
- Nell

you need two variables, say i and j. Initially it looks like this
i = 1;
j = 1;
1. Add both and keep the sum in a variable.
2. copy j to i
3. copy sum to j and repeat the process

subith86 17 Junior Poster

hi,
i need to ask how to generate the negative answer?
i have one formula. But always give me positive answer..
For exmaple:
AllocatDiff2 = 100 * -0.05;

hope somebody can help me ...ASAP!! Thanks ...

is AllocatDiff2 and unsigned int?

subith86 17 Junior Poster

But that was not the question! The answer generated was correct under the conditions set by the teacher.

I know. But I still I feel my solution is not the perfect one. Why because, I gave away a non-generic solution. A code is not good if it works in some scenario but doesn't work in other. I gave a hint about the loop hole so that Mxous could put his own effort into correcting it.

subith86 17 Junior Poster

Very interesting set up subith. Adds one every time it is over a value... To make it display F instead of D though:

grade_index = 2*(score/55) + score/65 + score/75 + score/85;
     
    char grade = 70;
    grade = grade - grade_index;
    printf("%c", grade);

It Works!
Such a simple solution that I probably would never have come up with...

Thanks for everyone's help.

It's not a perfect solution like you think though it works with your requirement. Imagine a case where F grade is for 0-35 score. Then you need some more changes :)

subith86 17 Junior Poster

can you atleast tell which line you are trying to delete the index.

subith86 17 Junior Poster

What problem are you facing? Post the error that you get.
Also please edit your first post by aligning the code properly and wrap [code] tag so that it is easily understandable for us to analyze.

subith86 17 Junior Poster

You are passing the pointer by value. And you are swapping the copy of the actual pointers in swap() function. When it comes out from the function, the pointers' copies go out of scope and hence no swap happens.

One solution is to pass the pointer by reference.

Other solution is to swap the values rather than swap the pointers (in swap() function) like shown below.

void swap(int *x,int *y)
{
    static int temp;
    temp=*x;
    *x=*y;
    *y=temp;
}
subith86 17 Junior Poster

How about this??? :cool:

unsigned int grade_index;
    unsigned int score = 35; //this is your score. use scanf to get it.

    grade_index = score/55 + score/65 + score/75 + score/85;

    char grade = 69;
    grade = grade - grade_index;
    printf("%c", grade);
subith86 17 Junior Poster

What I understand from your requirement is that your Swarm object will contain Particle(s). Each Particle has a unique dimension_id. Why can't you use map in Swarm class. A map where the key is dimension_id and value is a Particle object.

Please correct me if my understanding of your requirement is wrong.

subith86 17 Junior Poster

So I guess the task is to turn 5000000000000 into {0x27395000, 0x0000048C}.

Yes, exactly and thank you once again for another great suggestion. This much info is enough for me to proceed. I will get back after I finish. Don't know when, b'cos this is something like a hobby when I do only during free time :)

BytNum -- ByteNum[x] = StrNum[x] - '0';

I didn't get what you are trying to do here. Could you please explain.

And I agree with the fact that this solution will do addition and subtraction with ease. But what about multiplication? Am I supposed to take each byte by byte and multiply just like manual multiplication?

subith86 17 Junior Poster

Choice #1,
no delimiters. Because you can't expect the user to be too smart to put delimiters or to enter hex. As one of my colleagues say, we have to write a code keeping in mind that your end user is the dumbest in the world :P

subith86 17 Junior Poster

A vector of unsigned ints and a bool for the sign seems better.

Yes, I agree!!

Do everything in hex.

I agree on this too as this makes splitting easier.

READ the numbers in as a string in hex.

Actually I intend to read numbers as a string in decimal (not hex). I will convert it to hex string (using stringstream) for splitting purpose. But I find an issue here. If the number in the string is greater than the integer limits, conversion fails. I am finding a way to solve this. If you have any ideas, please come forward.

subith86 17 Junior Poster

I am trying to implement my own version of BigInteger which can hold an arbitrary big integer. I have posted my BigInteger.h file here and I need your suggestions if there is any better design for this.

1. std::string private member will hold the BigInteger in the form of string.

2. Addition :
a. take each character from right
b. convert it to int.
d. Add both. hold the sum in one variable and carry over in another.
e. convert sum to string and append to the result string.
f. carry over variable to be used in the next set of addition.
g. repeat till the left most end of the string.


3. This is very much a preliminary version. In the future, I also plan to overload "=" operator so that I can assign values directly without using constructors.

I'm a bit skeptical about the 1st point. Is there any better way to implement this other than using strings? Also 2.b and 2.e. Is there any other solution other than converting a string to int, adding and then converting back to string?

#include <iostream>
#include <string>
#include <sstream>

class BigInteger
{
    private:
        ////////////////////////////////////////////////////////////////////////
        // The big integer will be stored as a string
        // in this private member.
        ////////////////////////////////////////////////////////////////////////
        std::string _number;

    public:
        ////////////////////////////////////////////////////////////////////////
        // Default constructor to initialize _number.
        // Sets the value of _number to "0".
        ////////////////////////////////////////////////////////////////////////
        //  Parameters  :    none
        ////////////////////////////////////////////////////////////////////////
        BigInteger():_number("0"){}

        ////////////////////////////////////////////////////////////////////////
        // …
subith86 17 Junior Poster

have you included iostream?