Algorithm


Problem Name: 30 days of code - Day 27: Testing

Problem Link: https://www.hackerrank.com/challenges/30-testing/problem?isFullScreen=true

This problem is about unit testing.

 

Your company needs a function that meets the following requirements:

 

  • For a given array of
  • integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, it returns the smallest one.
  • If an empty array is passed to the function, it raises an exception. A colleague has written this method. The implementation in Python is listed below. Implementations in other languages can be found in the code template.

 

def minimum_index(seq):
    if len(seq) == 0:
        raise ValueError("Cannot get the minimum value index from an empty sequence")
    min_idx = 0
    for i in range(1, len(seq)):
        if a[i] < a[min_idx]:
            min_idx = i
    return min_idx

A coworker has prepared functions that will perform the tests and validate return values. Finish the implementation of 3 classes to provide data and expected results for the tests.

Complete the following methods.

 

In the class TestDataEmptyArray:

 

  • get_array() returns an empty array

 

In the class TestDataUniqueValues:

 

  • get_array() returns an array of size at least 2 with all unique elements
  • get_expected_result() returns the expected minimum value index for this array

 

In the class TestDataExactlyTwoDifferentMinimums:

 

  • get_array() returns an array where the minimum value occurs at exactly 2 indices
  • get_expected_result() returns the expected index

 

Take a look at the code template to see the exact implementation of functions that your colleague already implemented.

Note: The arrays are indexed from 0.

 

 

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


#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;
}

struct TestDataEmptyArray {
    static vector<int> get_array() { return {}; }
};

struct TestDataUniqueValues {
    static vector<int> get_array() { return {1, 2}; }
    static int get_expected_result() { return 0; }
};

struct TestDataExactlyTwoDifferentMinimums {
    static vector<int> get_array() { return {1, 1}; }
    static int get_expected_result() { return 0; }
};

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;
}
Copy The Code & Try With Live Editor

#2 Code Example with Java Programming

Code - Java Programming


import java.util.*;

public class Solution {

    public static int minimum_index(int[] seq) {
        if (seq.length == 0) {
            throw new IllegalArgumentException("Cannot get the minimum value index from an empty sequence");
        }
        int min_idx = 0;
        for (int i = 1; i  <  seq.length; ++i) {
            if (seq[i] < seq[min_idx]) {
                min_idx = i;
            }
        }
        return min_idx;
    }

    static class TestDataEmptyArray {
    	// Returns an empty array.
        public static int[] get_array() {
            return new int[0];
        }
    }

    static class TestDataUniqueValues {
    	// Returns an array of size at least 2 with all unique elements
        public static int[] get_array() {
            return new int[]{5,8,2,4};
        }

        // Returns the expected minimum value index for this array
        public static int get_expected_result() {
            return 2;
        }
    }

    static class TestDataExactlyTwoDifferentMinimums {
    	// Returns an array where there are exactly two different minimum values
        public static int[] get_array() {
            return new int[]{5,3,9,1,1,5,6,7};
        }

        // Returns the expected minimum value index for this array.
        public static int get_expected_result() {
            return 3;
        }
    }

    public static void TestWithEmptyArray() {
        try {
            int[] seq = TestDataEmptyArray.get_array();
            int result = minimum_index(seq);
        } catch (IllegalArgumentException e) {
            return;
        }
        throw new AssertionError("Exception wasn't thrown as expected");
    }

    public static void TestWithUniqueValues() {
        int[] seq = TestDataUniqueValues.get_array();
        if (seq.length  <  2) {
            throw new AssertionError("less than 2 elements in the array");
        }

        Integer[] tmp = new Integer[seq.length];
        for (int i = 0; i  <  seq.length; ++i) {
            tmp[i] = Integer.valueOf(seq[i]);
        }
        if (!((new LinkedHashSet < Integer>(Arrays.asList(tmp))).size() == seq.length)) {
            throw new AssertionError("not all values are unique");
        }

        int expected_result = TestDataUniqueValues.get_expected_result();
        int result = minimum_index(seq);
        if (result != expected_result) {
            throw new AssertionError("result is different than the expected result");
        }
    }

    public static void TestWithExactlyTwoDifferentMinimums() {
        int[] seq = TestDataExactlyTwoDifferentMinimums.get_array();
        if (seq.length  <  2) {
            throw new AssertionError("less than 2 elements in the array");
        }

        int[] tmp = seq.clone();
        Arrays.sort(tmp);
        if (!(tmp[0] == tmp[1] && (tmp.length == 2 || tmp[1]  <  tmp[2]))) {
            throw new AssertionError("there are not exactly two minimums in the array");
        }

        int expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result();
        int result = minimum_index(seq);
        if (result != expected_result) {
            throw new AssertionError("result is different than the expected result");
        }
    }

    public static void main(String[] args) {
        TestWithEmptyArray();
        TestWithUniqueValues();
        TestWithExactlyTwoDifferentMinimums();
        System.out.println("OK");
    }
}
Copy The Code & Try With Live Editor

#3 Code Example with Python Programming

Code - Python Programming


def minimum_index(seq):
    if len(seq) == 0:
        raise ValueError("Cannot get the minimum value index from an empty sequence")
    min_idx = 0
    for i in range(1, len(seq)):
        if seq[i] < seq[min_idx]:
            min_idx = i
    return min_idx

class TestDataEmptyArray:
    def get_array():
        return []
    
class TestDataUniqueValues:
    def get_array():
        return [1,2,3]
    def get_expected_result():
        return 0
class TestDataExactlyTwoDifferentMinimums:
    def get_array():
        return [1,1,3]
    def get_expected_result():
        return 0


def TestWithEmptyArray():
    try:
        seq = TestDataEmptyArray.get_array()
        result = minimum_index(seq)
    except ValueError as e:
        pass
    else:
        assert False


def TestWithUniqueValues():
    seq = TestDataUniqueValues.get_array()
    assert len(seq) >= 2

    assert len(list(set(seq))) == len(seq)

    expected_result = TestDataUniqueValues.get_expected_result()
    result = minimum_index(seq)
    assert result == expected_result


def TestiWithExactyTwoDifferentMinimums():
    seq = TestDataExactlyTwoDifferentMinimums.get_array()
    assert len(seq) >= 2
    tmp = sorted(seq)
    assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2])

    expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result()
    result = minimum_index(seq)
    assert result == expected_result

TestWithEmptyArray()
TestWithUniqueValues()
TestiWithExactyTwoDifferentMinimums()
print("OK")

Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Day 26: Nested Logic solution in Hackerrank - Hacerrank solution C, C++, C#, GO, java, Js, Python & PHP in 30 days of code
Next
[Solved] Day 28: RegEx, Patterns, and Intro to Databases solution in Hackerrank - Hacerrank solution C, C++, C#, GO, java, Js, Python & PHP in 30 days of code