Proving your Programming Skills

General idea

A = a
B = b

A = A*B = (ab)
B = b

B = A/B = (ab/b) = a
A = (ab)

A = A/B = (ab/a) = b

A = b
B = a
 
To be quite blunt, how does swap() prove you can program! It's so K&R..

There's more to life than that.


1. If a and b are double, who cares?
2. It they are array, use std::move.
 
nope! you are using two extra temp variables A & B
a and b are given, you have no more resources

no i meant a and b as the values themselves, i shouldve clarified.

A, B are the var names.

example

int A = 4
int B = 5

A *=B -> A = 20
B = A/B -> B = 4
A = A/B ->A= 5

now A = 5, B = 4
 

I'm being pedantic, 'program' is the wrong word (use 'variable'), but was copied verbatim..

a=a+b;
b=a-b;
a=a-b;

I have a nasty feeling that several(3?) temp variables are generated by the compiler. Am I missing something??

And two arithmetic operations! Yikes. Take and b close to each other to get catastrophic cancellation. Round-off errors are also possible.

BTW that nameless blog looks like cookie spam.


//Now try it with matrices!
 
Last edited:
Example of round off.

Code:
// Roundoff.cpp

// DD

#include <iostream>
#include <iomanip>

namespace NOT_STL_SWAP
{
    template <typename T>
    void swap(T& a, T& b)
    {
        a = a + b; // a += b !!
        b = a - b;
        a = a - b;
    }

}

int main()
{
    using NOT_STL_SWAP::swap;

    float a = 1.0F;
    float b = 1.0001012345679F;

    int N = 1;
    for (int n = 1; n <= N; ++n)
    {
        swap(a, b);
    }
    std::cout << std::setprecision(8) << a << ", " << b << '\n';

    a = 1.0F;
    b = 1.0001012345679F;
    for (int n = 1; n <= N; ++n)
    {
        std::swap(a, b);
    }
    std::cout << std::setprecision(8) << a << ", " << b << '\n';

    return 0;
}
 
Code:
namespace YET_NOT_STL_SWAP
{
    template <typename T>
    void swap(T& a, T& b)
    {
        a * / b;
        b = a / b;
        a = a / b;
    }

}
no i meant a and b as the values themselves, i shouldve clarified.

A, B are the var names.

example

int A = 4
int B = 5

A *=B -> A = 20
B = A/B -> B = 4
A = A/B ->A= 5

now A = 5, B = 4

Have you tried this in real life? * and / are slow and inaccurate.
 
Last edited:
Back
Top Bottom