Skip to content

Commit

Permalink
Added minimum swaps to make arrays equal
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Oct 14, 2024
1 parent a3a04d5 commit d1df6ba
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/algorithms/sorting/minimum_swaps.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#ifndef MINIMUM_SWAPS_H
#define MINIMUM_SWAPS_H

#ifdef __cplusplus
#include <iostream>
#include <vector>
#include <cassert>
#include <map>
#endif

/**
* @brief minimum swaps function.
* It computes the minimum swaps to make a equal to b
* @param a: vector<int>
* @param b: vector<int>
* @return int: the minimum number of swaps to make array a equal to array b
*/
int minimum_swaps(std::vector<int> &a, std::vector<int> &b) {
assert(a.size() == b.size());
int n = int(a.size());
auto solve = [&](std::vector<int> &arr) -> int {
std::vector<std::pair<int, int> > positions;
for(int i = 0; i<n; i++) {
int pos = i, value = arr[i];
positions.push_back({value, pos});
}

std::sort(positions.begin(), positions.end());

std::vector<bool> visited(n, false);

int min_swaps = 0;
for(int i = 0; i<n; i++) {
if(visited[i] || positions[i].second == i) {
continue;
}

int cycle_size = 0, j = i;
while(!visited[j]) {
visited[j] = 1;
j = positions[j].second;
cycle_size++;
}

min_swaps += (cycle_size - 1);
}

return min_swaps;
};

std::map<int, int> m;
for(int i = 0; i<n; i++) {
m[b[i]] = i;
}

for(int i = 0; i<n; i++) {
b[i] = m[a[i]];
}

return solve(b);
}



#endif
36 changes: 36 additions & 0 deletions tests/algorithms/sorting/minimum_swaps.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include "../../../src/algorithms/sorting/minimum_swaps.h"
#include "../../../third_party/catch.hpp"
#include <random>
#include <vector>
#include <cstdlib>


TEST_CASE("Testing minimum swaps [1]") {
std::vector<int> a {3, 6, 4, 8};
std::vector<int> b {4, 6, 8, 3};

REQUIRE(minimum_swaps(a, b) == 2);
}

TEST_CASE("Testing minimum swaps [2]") {
std::vector<int> a {1, 2, 3, 4};
std::vector<int> b {4, 3, 2, 1};

REQUIRE(minimum_swaps(a, b) == 2);
}

TEST_CASE("Testing minimum swaps [3]") {
std::vector<int> a {1, 2, 3, 4, 5, 6, 7};
std::vector<int> b {1, 2, 3, 4, 5, 6, 7};

REQUIRE(minimum_swaps(a, b) == 0);
}

TEST_CASE("Testing minimum swaps [4]") {
std::vector<int> a(100), b(100);
iota(a.begin(), a.end(), 1);
iota(b.begin(), b.end(), 1);

std::swap(a[0], a[99]);
REQUIRE(minimum_swaps(a, b) == 1);
}

0 comments on commit d1df6ba

Please sign in to comment.