Answer to Question #198391 in C++ for Mohraeel salah

Question #198391

Solve the problem of sparse 2- dimensional array

A sparse array is an array in which most of the elements have the same value (known 

as the default value—usually 0 or null). The occurrence of zero elements in a large

array is inefficient for both computation and storage. It is required to implement 

sparse 2- dimensional array in more efficient way. Your implementation should 

allow:

 Adding new value in a specific index.

 Removing a value from specific index.

 Search for a value and return its index if found.

 Return a value from specific index.


1
Expert's answer
2021-05-25T23:09:04-0400
#include <iostream>
#include <map>
#include <pair>

using namespace std;

class SparseArray {
private:
    map<pair<int,int>,int> elems;
public:
    void set(int, int, int);
    void remove(int, int);
    pair<int,int> find(int);
    int get(int, int);
};

void SparseArray::set(int x, int y, int item) {
    pair<int,int> p = {x, y};
    auto iter = this->elems.find(p);
    if (iter != this->elems.end()) {
        this->elems[p] = item;
    } else {
        this->elems.insert(p, item);
    }
}

void SparseArray::remove(int x, int y) {
    pair<int,int> p = {x, y};
    auto iter = this->elems.find(p);
    if (iter != this->elems.end()) {
        this->elems.erase(iter);
    }
}

pair<int,int> SparseArray::find(int item) {
    for (auto it = this->elems.begin(); it != this->elems.end(); it += 1) {
        if ((*it).second == item) {
            return (*it).first;
        }
    }
    return NULL;
}

int SparseArray::get(int x, int y) {
    pair<int,int> p = {x, y};
    auto iter = this->elems.find(p);
    if (iter != this->elems.end()) {
        return (*iter).second;
    } else {
        return -1;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog