这是一个问题:对于给定的整数数组,该函数返回数组中具有最小值的元素的索引。如果有多个元素具有最小值,则返回的索引应该是最小的。 如果将空数组传递给函数,则应该引发异常。
get_array()方法必须返回一个空数组。 类TestDataUniqueValues中的get_array()方法必须返回一个大小至少为2且包含所有唯一元素的数组,而此类的方法get_expected_result()必须返回此数组的预期最小值索引。
类TestDataExactlyTwoDifferentMinimums中的#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cassert>
#include <set>
using namespace std;
int minimum_index(vector<int> seq) {
if (seq.empty()) {
throw invalid_argument("Cannot get the minimum value index from an
empty sequence");
}
int min_idx = 0;
for (int i = 1; i < seq.size(); ++i) {
if (seq[i] < seq[min_idx]) {
min_idx = i;
}
}
return min_idx;
}
class TestDataEmptyArray {
public:
static vector<int> get_array() {
vector<int> v;
return v;
}
};
class TestDataUniqueValues {
public:
static vector<int> get_array() {
vector<int> v;
int a[100];
for(int i=0;i<100;i++){
a[i]=0;
}
int x;
x=rand()%100;
a[x]=1;
v.push_back(x);
x=rand()%100;
if(a[x]==0){
v.push_back(x);
}
for(int i=0;i<10;i++){
int x=rand()%100;
if(a[x]==0){
v.push_back(x);
a[x]=1;
}
}
return v;
}
static int get_expected_result() {
vector<int> v=TestDataUniqueValues::get_array();
int index=0,min=1000;
for(int i=0;i<v.size();i++){
if(v[i]<min){
index=i;
min=v[i];
}
}
return index;
}
};
class TestDataExactlyTwoDifferentMinimums {
public:
static vector<int> get_array() {
vector<int> v;
int x=rand()%1000 +1;
v.push_back(x);
for(int i=0;i<10;i++){
int x=rand()%1000+1;
v.push_back(x);
}
int min=100000;
for(int i=0;i<v.size();i++){
if(v[i]<min){
min=v[i];
}
}
v.push_back(min);
return v;
}
static int get_expected_result() {
vector<int> v=TestDataExactlyTwoDifferentMinimums::get_array();
int index,min=100000;
for(int i=0;i<v.size();i++){
if(v[i]<min){
index=i;
min=v[i];
}
}
return index;
}
};
void TestWithEmptyArray() {
try {
auto seq = TestDataEmptyArray::get_array();
auto result = minimum_index(seq);
} catch (invalid_argument& e) {
return;
}
assert(false);
}
void TestWithUniqueValues() {
auto seq = TestDataUniqueValues::get_array();
assert(seq.size() >= 2);
assert(set<int>(seq.begin(), seq.end()).size() == seq.size());
auto expected_result = TestDataUniqueValues::get_expected_result();
auto result = minimum_index(seq);
assert(result == expected_result);
}
void TestWithExactlyTwoDifferentMinimums() {
auto seq = TestDataExactlyTwoDifferentMinimums::get_array();
assert(seq.size() >= 2);
auto tmp = seq;
sort(tmp.begin(), tmp.end());
assert(tmp[0] == tmp[1] and (tmp.size() == 2 or tmp[1] < tmp[2]));
auto expected_result =
TestDataExactlyTwoDifferentMinimums::get_expected_result();
auto result = minimum_index(seq);
assert(result == expected_result);
}
int main() {
TestWithEmptyArray();
TestWithUniqueValues();
TestWithExactlyTwoDifferentMinimums();
cout << "OK" << endl;
return 0;
}