Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
T

Tarun Jha

@Tarun Jha
About
Posts
118
Topics
43
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • To insert a node at the back of a XOR doubly linked list
    T Tarun Jha

    here is the method to insert a node at the front in the XORed doubly linked list or also known as memory efficient doubly linked list :

    // To write a memory efficient linked list
    #include using namespace std;

    // Node structure of a memory efficient doubly linked list
    class Node {
    public:
    int data;
    Node *npx; // XOR of next and previous node
    };

    // return XORed value of the node address
    Node *XOR(Node *a, Node *b){
    return ((Node *)( (uintptr_t)(a) ^ (uintptr_t)(b) ));
    }

    // insert a node at the beggining of the XORed linked list and makes the newly inserted node as head
    void insert(Node **head_ref, int data){
    // allocate memory for new node
    Node *new_node = new Node();
    new_node->data = data;

    // since node is inserted at the beggining, npx of the new node will always be XOR of curent head and null
    new\_node->npx = XOR((\*head\_ref), nullptr);
    
    // if the linked list is not empty, then npx of current head node will be XOR of new node and node next to current head
    if(\*head\_ref != nullptr){
        // (\*head\_ref)->npx is XOR of null and next.
        // so if we do XOR of it with null, we get next
        Node \*next = XOR((\*head\_ref)->npx, nullptr);
        (\*head\_ref)->npx = XOR(new\_node, next);
    }
    
    // change head
    \*head\_ref = new\_node;
    

    }

    // prints contents of doubly linked list in forward direction
    void printList(Node *head){
    Node *curr = head, *prev = nullptr, *next;

    cout << "Following are the nodes of Linked List: \\n";
    
    while(curr != nullptr) {
        // print current node
        cout << curr->data << " ";
    
        // get the address of next node : curr->npa is next^prev,
        // so curr->npx^prev will be next^prev^prev which is next
        next = XOR(prev, curr->npx);
    
        // update prev and curr for next iteration
        prev = curr;
        curr = next;
    }
    

    }

    // Driver function
    int main(){
    Node *head = nullptr;
    insert(&head, 10);
    insert(&head, 20);
    insert(&head, 30);
    insert(&head, 40);
    insert(&head, 50);
    insert(&head, 60);

    printList(head);
    
    return 0;
    

    }

    Here is the code i have tried to put an element at the back of the list:

    Node *insert(Node **last, int data){
    // allocate memory for new node
    Node *new_node = new Node();
    new_node->data = data;

    new\_node->npx = XOR(\*last, nullptr);
    
    if(\*last != nullptr) {
    	Node \*prev = XOR((\*last)->npx, nullptr)
    
    ATL / WTL / STL data-structures performance announcement

  • Rearrange array in alternating positive & negative items with O(1) extra space, while keeping the order of the elements maintained.
    T Tarun Jha

    The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index, or it is positive and at even index. Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the sub-array between these two elements (including these two).

    /* C++ program to rearrange positive and negative integers in alternate
    fashion while keeping the order of positive and negative numbers. */
    #include
    #include
    using namespace std;

    void printArray(int arr[], int n);

    // Utility function to right rotate all elements between [outofplace, cur]
    void rightrotate(int arr[], int n, int outofplace, int cur)
    {
    char tmp = arr[cur];
    for (int i = cur; i > outofplace; i--)
    arr[i] = arr[i-1];
    arr[outofplace] = tmp;
    }

    void rearrange(int arr[], int n)
    {
    int outofplace = -1;

    for (int index = 0; index < n; index ++)
    {
        if (outofplace >= 0)
        {
            // find the item which must be moved into the out-of-place
            // entry if out-of-place entry is positive and current
            // entry is negative OR if out-of-place entry is negative
            // and current entry is negative then right rotate
            //
            // \[...-3, -4, -5, 6...\] -->   \[...6, -3, -4, -5...\]
            //      ^                          ^
            //      |                          |
            //     outofplace      -->      outofplace
            //
            if (((arr\[index\] >= 0) && (arr\[outofplace\] < 0))
                || ((arr\[index\] < 0) && (arr\[outofplace\] >= 0)))
            {
                rightrotate(arr, n, outofplace, index);
                printArray(arr, n);
    
                // the new out-of-place entry is now 2 steps ahead
                if (index - outofplace > 2)
                    outofplace = outofplace + 2;
                else
                    outofplace = -1;
            }
        }
    
    
        // if no entry has been flagged out-of-place
        if (outofplace == -1)
        {
            // check if current entry is out-of-place
            if (((arr\[index\] >= 0) && (!(index & 0x01)))      // what does (index & 0x01) means ??
                || ((arr\[index\] < 0) && (index & 0x01)))
            {
                outofplace = index;
            }
        }
    }
    

    }

    // A utility function to print an arra

    C / C++ / MFC c++ database data-structures tools question

  • Find element at given index after a number of rotations
    T Tarun Jha

    please check the question again i have edited it and also provided with the link to the original problem

    C / C++ / MFC database c++ algorithms data-structures

  • Find element at given index after a number of rotations
    T Tarun Jha

    please check again i have elaborated it and have also provided link to the original question

    C / C++ / MFC database c++ algorithms data-structures

  • Find element at given index after a number of rotations
    T Tarun Jha

    if you know the logic can you elaborate. please

    C / C++ / MFC database c++ algorithms data-structures

  • Find element at given index after a number of rotations
    T Tarun Jha

    The author's code : An array consisting of N integers is given. There are several Right Circular Rotations of range[L..R] that we perform. After performing these rotations, we need to find element at a given index.

    Quote:

    Input : arr[] : {1, 2, 3, 4, 5} ranges[] = { {0, 2}, {0, 3} } index : 1 Output : 3 Explanation : After first given rotation {0, 2} arr[] = {3, 1, 2, 4, 5} After second rotation {0, 3} arr[] = {4, 3, 1, 2, 5} After all rotations we have element 3 at given index 1.

    // CPP code to rotate an array
    // and answer the index query
    #include using namespace std;

    // Function to compute the element at
    // given index
    int findElement(int arr[], int ranges[][2],
    int rotations, int index)
    {
    for (int i = rotations - 1; i >= 0; i--) {

        // Range\[left...right\]
        int left = ranges\[i\]\[0\];
        int right = ranges\[i\]\[1\];
    
        // Rotation will not have any effect
        if (left <= index && right >= index) {
            if (index == left)
                index = right;
            else
                index--;
        }
    }
    
    // Returning new element
    return arr\[index\];
    

    }

    // Driver
    int main()
    {
    int arr[] = { 1, 2, 3, 4, 5 };

    // No. of rotations
    int rotations = 2;
    
    // Ranges according to 0-based indexing
    int ranges\[rotations\]\[2\] = { { 0, 2 }, { 0, 3 } };
    
    int index = 1;
    
    cout << findElement(arr, ranges, rotations, index);
    
    return 0;
    

    }

    Quote:

    and the authors logic:

    Method : Efficient We can do offline processing after saving all ranges. Suppose, our rotate ranges are : [0..2] and [0..3] We run through these ranges from reverse. After range [0..3], index 0 will have the element which was on index 3. So, we can change 0 to 3, i.e. if index = left, index will be changed to right. After range [0..2], index 3 will remain unaffected. So, we can make 3 cases : If index = left, index will be changed to right. If index is not bounds by the range, no effect of rotation. If index is in bounds, index will have the element at index-1. i tried buy brute fore method and it took O(n^2) time complexity. So i want to understand this logic, can someone please explain the logic. i have edited the information given, and it concludes all the information given by the

    C / C++ / MFC database c++ algorithms data-structures

  • To find the angle of turn in a car racing game in C++/SFML
    T Tarun Jha

    thank you

    Managed C++/CLI c++ game-dev performance question

  • To find the angle of turn in a car racing game in C++/SFML
    T Tarun Jha

    in the code below i would like to know how the logic of finding the angle at a turn works.

    int main()
    {
    RenderWindow app(VideoMode(640, 480), "Car Racing Game!");
    app.setFramerateLimit(60);

    Texture t1, t2;
    t1.loadFromFile("images/background.png");
    t2.loadFromFile("images/car.png");
    
    Sprite sBackground(t1), sCar(t2);
    sCar.setPosition(300, 300);
    sCar.setOrigin(22, 22);
    
    float x = 300, y = 300;
    float speed = 0, angle = 0;
    float maxSpeed = 12.0;
    float acc = 0.2, dec = 0.3;
    float turnSpeed = 0.08;
    
    while (app.isOpen())
    {
    	Event event;
    	while (app.pollEvent(event))
    	{
    		if (event.type == Event::Closed)
    			app.close();
    		if (Keyboard::isKeyPressed(Keyboard::Escape))
    			app.close();
    	}
    
    	bool Up = false, Right = false, Down = false, Left = false;
    	if (Keyboard::isKeyPressed(Keyboard::Up))		Up = true;
    	if (Keyboard::isKeyPressed(Keyboard::Right))	Right = true;
    	if (Keyboard::isKeyPressed(Keyboard::Down))		Down = true;
    	if (Keyboard::isKeyPressed(Keyboard::Left))		Left = true;
    
    	// Car Movements
    	if (Up && speed < maxSpeed)
    		if (speed < 0)	speed += dec;
    		else speed += acc;
    
    	if (Down && speed > -maxSpeed)
    		if (speed > 0)	speed -= dec;
    		else speed -= acc;
    
    	if (!Up && !Down)
    		if (speed - dec > 0)	speed -= dec;
    		else if (speed + dec < 0)	speed += dec;
    		else speed = 0;
                
                //--------- How this logic works ?
    	if (Right && speed != 0)	angle += turnSpeed \* speed / maxSpeed;
    	if (Left && speed != 0)		angle -= turnSpeed \* speed / maxSpeed;
    
    	x += sin(angle) \* speed ;
    	y -= cos(angle) \* speed ;
          
               //------------- //
    
    
    	// Draw
    	app.clear(Color::White);
    	app.draw(sBackground);
    
    	sCar.setPosition(x, y);
    	sCar.setRotation(angle \* 180 / 3.141592) ;
    	sCar.setColor(Color::Red);
    	app.draw(sCar);
    
    	app.display();
    }
    return 0;
    

    }

    How the below logic works ?

    Quote:

    if (Right && speed != 0) angle += turnSpeed * speed / maxSpeed; if (Left && speed != 0) angle -= turnSpeed * speed / maxSpeed; x += sin(angle) * speed ; y -= cos(angle) * speed ;

    Thank you

    Managed C++/CLI c++ game-dev performance question

  • using user-defined data type as data-member of a class.
    T Tarun Jha

    Here is a class called Animation, and it has a function called Update as shown in the code below.

    class Animation
    {
    private:
    Vector2u imageCount; // contains the number of total images in row and total no. of coloumns , in this case (3, 9)
    Vector2u currentImage; // acts as the limiter.
    float totalTime; // the total time taken by whole animation.
    float switchTime; // the time duration btw to images.

    public:
    // Texture * texture -> takes the whole image.
    // Vector2u imageCount -> counts the number of images in each row, and total number of coloumn.
    // float switchTime -> time btw 2 images.
    Animation(Texture* texture, Vector2u imageCount, float switchTime);
    ~Animation();

    IntRect uvRect;						// sets the height, width, top, and left corner of the image to be printed on the screen.
    
    void Update(int row, float deltaTime, bool faceRight );		// float deltaTime -> gives the FPS of the machine, acc. to which the switch bte images is maintained.
    

    };
    Animation::Animation(Texture* texture, Vector2u imageCount, float switchTime) {
    this->imageCount = imageCount;
    this->switchTime = switchTime;
    totalTime = 0.0f;

    // here we have set the initial image position-> first position
    currentImage.x = 0;
    currentImage.y = 0;
    
    // here we are setting height & width of each image.
    uvRect.width = texture->getSize().x / static\_cast(imageCount.x);
    uvRect.height = texture->getSize().y / static\_cast(imageCount.y);
    

    }

    Animation::~Animation()
    {
    }

    // this is the function i am talking about
    // it takes argument which are the data members of player class.
    void Animation::Update(int row, float deltaTime, bool faceRight) {
    currentImage.y = row;
    totalTime += deltaTime; // deltaTime is added to the totalTime.

    if (totalTime >= switchTime) {
    	totalTime -= switchTime;
    	currentImage.x++;								// every time totalTime >= switchTime, incrementing currentImage.x
    
    	if (currentImage.x >= imageCount.x) {			// when currentImage.x >= imageCount.x, the currentImage.x = 0.	
    		currentImage.x = 0;	
    	}
    }
    
    uvRect.top = currentImage.y \* uvRect.height;
    
    // to turn the player to each side, left or right.
    if (faceRight) {
    	uvRect.left = currentImage.x \* uvRect.width;			// if the faceRight is True.
    	uvRect.width = abs(uvRect.width) ;
    }
    else {
    	uvRect.left = (currentImage.x + 1) \* abs(uvRect.width);		// if the faceRight is false .
    	uvRect.width = -abs(uvRect.width);
    
    }
    

    }

    and the is 2nd class called player, in which i have

    Managed C++/CLI announcement

  • using dynamic_cast with template classes.
    T Tarun Jha

    thank's

    C / C++ / MFC help question

  • using dynamic_cast with template classes.
    T Tarun Jha

    Quote:

    return (Num::val * Num::val);

    but i have already inherited all the members of the base class to the derived class, then why i need to use scope resolution operator to point where to look for val ?

    C / C++ / MFC help question

  • i would like to be a programmer
    T Tarun Jha

    you need to love it, you need to have fun while solving problems, you need to have patience and open mind, you need to be regular, you need lot's of practice and good books, and the rest will follow. that's what i have experienced till date.

    C / C++ / MFC question

  • using dynamic_cast with template classes.
    T Tarun Jha

    i added * after SqrNum but it is still giving that error .

    C / C++ / MFC help question

  • how to correct an segmentation fault ?
    T Tarun Jha

    thank you !

    C / C++ / MFC question com graphics data-structures json

  • using dynamic_cast with template classes.
    T Tarun Jha

    // Demonstrate dynamic_cast on template classes.
    #include using namespace std;

    template class Num {
    protected:
    T val;
    public:
    Num(T x) { val = x;}
    virtual T getval() { return val; }
    };

    template class SqrNum : public Num {
    public:
    SqrNum(T x) : Num(x) {}
    T getval() { return (val * val); }
    };

    int main(){
    Num *bp, numInt_ob(2);
    SqrNum *dp, sqrInt_ob(3);
    Num numDouble_ob(3.3);

    bp = dynamic\_cast\*> (&sqrInt\_ob);          //sqrInt\_ob is from a derived class of Num.
    if(bp) {
        cout << "Cast from sqrNum\* to Num\* OK.\\n"
             << "Value is " << bp->getval() << endl;
    }
    else
        cout << "Error !\\n\\n";
    
    dp = dynamic\_cast\> (&numInt\_ob);        //numInt\_ob is base class object and SqrNum is a derived class.
    if(dp)
        cout << "Error !\\n";
    else {
        cout << "Cast from Num\* to SqrNum\* not OK.\\n"
             << "Can't cast a pointer to a base object into\\n"
             << "a pointer to a derived object\\n\\n";
    }
    
    bp = dynamic\_cast\*> (&numDouble\_ob);        //Num of type int & numDouble\_ob is of type Num
    if(bp)
        cout << "Error" << endl;
    else {
        cout << "Can't cast from Num\* to Num\*.\\n"
             << "These are 2 different types.\\n\\n";
    }
    
    return 0;
    

    }

    in the code above i m getting error that

    Quote:

    error: 'val' was not declared in this scope T getval() { return (val val); } ^~~

    but

    Quote:

    class SqrNum : public Num

    according to this the protected value in the base class should just work fine as protected value in the derived class, but it isn't ? How do i solve this problem ? EDIT : below is the working code:

    // Demonstrate dynamic_cast on template classes.
    #include
    using namespace std;

    template
    class Num {
    protected:
    T val;
    public:
    Num(T x) { val = x;}
    virtual T getval() { return val; }
    };

    template
    class SqrNum : public Num {
    public:
    SqrNum(T x) : Num(x) {}
    T getval() { return (Num::val * Num::val); }
    };

    int main(){
    Num *bp, numInt_ob(2);
    SqrNum *dp, sqrInt_ob(3);
    Num numDouble_ob(3.3);

    bp = dynamic\_cast\*> (
    
    C / C++ / MFC help question

  • how to correct an segmentation fault ?
    T Tarun Jha

    below is an hackerrank question link where i am encountering an segmentation falut. HackerRank[^] and this is my solution

    #include
    #include
    using namespace std;

    void fillVector(vector &temp, unsigned long number);
    void RotateVector(vector &arr1, vector &arr2, unsigned long k);

    int main(){
    unsigned long n,k,q;

    cin >> n >> k >> q;
    
    vector a, b;
    fillVector(a, n);
    fillVector(b, q);
    
    RotateVector(a, b, k);
    
    
    return 0;
    

    }

    //to rotate the vector by kth measure.
    void RotateVector(vector &arr1, vector &arr2, unsigned long k){
    unsigned long arraySize = arr1.size();
    unsigned long querySize = arr2.size();
    unsigned long rotation = k, i;
    unsigned long start = rotation%arraySize; //this was causing the problem.

    if(rotation rotatedArray;
    
    for(i=0; i &arr, unsigned long n){
    unsigned long temp;
    for(int i=0; i\> temp;
        arr.push\_back(temp);
    }
    

    }

    the above solution is giving segmentation fault and i am not able to detect it.(rest all the test-cases are passed) here are the links to that test case inputs : https://hr-testcases-us-east-1.s3.amazonaws.com/1884/input04.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1527377038&Signature=sA5C43bnnqyLeXwWA9L16en3rEE%3D&response-content-type=text%2Fplain and expected outputs : https://hr-testcases-us-east-1.s3.amazonaws.com/1884/output04.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1527377042&Signature=%2BSyDUj0B5DwySkSPGjiwfmB7MlE%3D&response-content-type=text%2Fplain Edit : Below is the working code:

    #include
    using namespace std;

    void fillVector(vector

    C / C++ / MFC question com graphics data-structures json

  • why passing argument by reference(&ref) in a template function shows error ? but works fine if arguments passed by pointer(*ptr) ?
    T Tarun Jha

    ohh... Thank you

    C / C++ / MFC help question

  • why passing argument by reference(&ref) in a template function shows error ? but works fine if arguments passed by pointer(*ptr) ?
    T Tarun Jha

    in the below program it i have used both ways i.e. passed arguments by reference and pointers. 1. Arguments by reference:

    #include
    using namespace std;

    template
    void swap(T &x, T &y){
    T temp = x;
    x = y;
    y = temp;
    }

    void fun(int m, int n, float a, float b){

    cout << "m & n before swap: " << m << " " << n << endl;
    swap(m, n);
    cout << "m & n after swap: " << m << " " << n << endl;
    
    cout << "i & j before swap: " << a << " " << b << endl;
    swap(a, b);
    cout << "i & j after swap: " << a << " " << b << endl;
    

    }

    int main(){
    fun(100, 200, 11.22, 33.44);

    return 0;
    

    }

    2. Arguments by pointers:

    #include
    using namespace std;

    template
    void swap(T *x, T *y){
    T temp = x;
    x = y;
    y = temp;
    }

    void fun(int m, int n, float a, float b){

    cout << "m & n before swap: " << m << " " << n << endl;
    swap(m, n);
    cout << "m & n after swap: " << m << " " << n << endl;
    
    cout << "i & j before swap: " << a << " " << b << endl;
    swap(a, b);
    cout << "i & j after swap: " << a << " " << b << endl;
    

    }

    int main(){
    fun(100, 200, 11.22, 33.44);

    return 0;
    

    }

    also if i pass the arguments by reference but make it a constant then also i works, why ?

    #include
    using namespace std;

    template
    void swap(const T &x, const T &y){
    T temp = x;
    x = y;
    y = temp;
    }

    void fun(int m, int n, float a, float b){

    cout << "m & n before swap: " << m << " " << n << endl;
    swap(m, n);
    cout << "m & n after swap: " << m << " " << n << endl;
    
    cout << "i & j before swap: " << a << " " << b << endl;
    swap(a, b);
    cout << "i & j after swap: " << a << " " << b << endl;
    

    }

    int main(){
    fun(100, 200, 11.22, 33.44);

    return 0;
    

    }

    Thank you.

    C / C++ / MFC help question

  • problem encountered by calling constructors explicitly.
    T Tarun Jha

    thank you

    C / C++ / MFC graphics help

  • problem encountered by calling constructors explicitly.
    T Tarun Jha

    here in the below program i have tried to pass the values of 1d matrix to the object of class Vector by using constructor explicit call.

    #include
    using namespace std;

    const int size = 3;
    class Vector {
    int *v;

    public:
    Vector(){
    v = new int[size];
    for(int i=0; iv[i] * y.v[i] ;
    return sum;
    }

    void display(){
        for(int i=0; i
    

    Quote:

    cout << "v1 = ";
    v1.display();
    
    cout << "v2 = ";
    v2.display();
    

    the above portion of code doesn't works as expected it gives,

    Output:

    Quote:

    6 3 9
    6 3 9
    v1 = 6 3 9
    v2 = 6 3 9
    v1 x v2 = 126

    Expected:

    Quote:

    Quote:

    1 2 3
    6 3 9
    v1 = 1 2 3
    v2 = 6 3 9
    v1 x v2 = 39

    Thank you

    C / C++ / MFC graphics help
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups