Quick actions

cmd+k|ctrl+k

Navigation

Languages

Function Pointers

Snippet info

Language

Cpp

Visibility

public

Author

rose0x4

Created

2018-02-06T03:28:05Z

Updated

2018-02-07T16:02:37Z

#include <iostream>
#include <vector>
#include <cmath>  // For pow().
using namespace std;

const int YEARS = 20;
const double INTEREST_RATE = 0.07;

/**
 * Applies a given function, `func`, to each element of the list, `numbers`, and
 * returns a list of results in the same order.
 */
vector<double> map(vector<double> numbers, double (*func)(double)) {
    vector<double> result(numbers.size());
    for (int i = 0; i < numbers.size(); i++) {
        result[i] = func(numbers[i]);
    }
    return result;
}

/**
 * Returns the amount compounded annually at the given interest rate for the
 * given number of years, when provided an initial quantity, `principal`.
 */
double compound_interest(double principal) {
    return principal * pow(1 + INTEREST_RATE, YEARS);
}

/**
 * Returns the number of years until a person with the given income (and no
 * expenses) becomes a millionaire, taking investment returns into account.
 */
double years_until_millionaire(double n) {
    int years = 0;
    double money = 0;
    while (true) {
        ++years;
        money += n;
        money = money * (1 + INTEREST_RATE);
        if (money > 1000000) {
            return years;
        }
    }
}

double print_element(double n) {
    cout << n << ",\t";
    return 0;
}

double times_a_thousand(double n) {
    return 1000 * n;
}

int main() {
    double (*func)(double) = times_a_thousand;
    cout << func(4) << endl << endl;
    
    vector<double> salaries = {56, 84, 117, 145, 211};
    vector<double> salaries_k = map(salaries, times_a_thousand);
    cout << "Initial:\t";
    map(salaries_k, print_element);
    cout << endl;
    
    cout << YEARS << " years at " << 100 * INTEREST_RATE << "%:\t";
    vector<double> compounded_money = map(salaries_k, compound_interest);
    map(compounded_money, print_element);
    cout << endl;
    
    cout << "Millionaire:\t";
    vector<double> years = map(salaries_k, years_until_millionaire);
    map(years, print_element);
    cout << endl;
    
    return 0;
}
INFO