C++ :: Aufgabe #363

1 Lösung Lösung öffentlich

Erzeugung einer Entfernungstabelle

Anfänger - C++ von hollst - 27.04.2021 um 20:13 Uhr
In der unendlich ausgedehnten euklidischen 2D-Eben wähle man zufällig N unterschiedliche Punkte P1, P2 ... PN. Die XY-Punktkoordinaten seien in Meter bemaßt.

Man schreibe eine Funktion, die P1 ... PN als Input annimmt und als Rückgabe eine Entfernungstabelle als (Double) N x N - Matrix ausgibt. D. h. die Hauptdiagonale ist mit Null besetzt und die Matrix ist bzgl. dieser symmetrisch.

Viel Spaß!

Lösungen:

vote_ok
von JKooP (18090 Punkte) - 16.05.2021 um 15:51 Uhr
C++ 17
Quellcode ausblenden C-Code
#include"DiffMatrix.h"

int main()
{
    // (1) Anzahl der Punkte im Koordinatensystem
    // (2) maximal positiver bzw. negativer Wert (x, y) eines Punktes (+/-)
    DiffMatrix d{ 20, 20 };

    d.print_coordinates();
    d.print_matrix();
}

.h
Quellcode ausblenden C-Code
#pragma once
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

struct Point {
    double x;
    double y;
};

class DiffMatrix
{
private:
    int _num_of_coordinates;
    int _max_value;
    vector<Point> _points{};
    vector<vector<double>> _matrix{};
    double get_diff(Point p1, Point p2);
    double get_rnd();

public:
    DiffMatrix(int num_of_coordinates, int max_value)
    {
        _num_of_coordinates = num_of_coordinates;
        _max_value = max_value;
        srand((unsigned int)time(0));
        _points = get_coordinates();
        _matrix = get_matrix();
    }
    vector<Point> get_coordinates();
    void print_coordinates();
    void print_matrix();
    vector<vector<double>> get_matrix();
};

.cpp
Quellcode ausblenden C-Code
#include "DiffMatrix.h"

double DiffMatrix::get_diff(Point p1, Point p2)
{
    return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
}

double DiffMatrix::get_rnd()
{
    return (2 * rand()) % _max_value * 2 - _max_value;
}

vector<Point> DiffMatrix::get_coordinates()
{
    vector<Point>v{};
    for (int i = 0; i < _num_of_coordinates; i++)
        v.push_back({ get_rnd(), get_rnd() });
    return v;
}

void DiffMatrix::print_coordinates()
{
    for (size_t i = 0; i < _points.size(); i++)
        cout << "P" << i + 1 << "(" << _points[i].x << ", " << _points[i].y << ")\n";
    cout << "\n";
}

void DiffMatrix::print_matrix()
{
    for (const auto& k : _matrix) {
        for (const auto& l : k)
            cout << fixed << setprecision(2) << l << "\t";
        cout << "\n\n";
    }
}

vector<vector<double>> DiffMatrix::get_matrix()
{
    vector<vector<double>> v;

    for (size_t i = 0; i < _points.size(); i++) {
        vector<double> v2;
        for (size_t k = 0; k < _points.size(); k++)
            v2.push_back(get_diff(_points[i], _points[k]));
        v.push_back(v2);
    }

    return v;
}