小组人数各异的结果数组的平均测试成绩

时间:2019-01-30 20:31:37

标签: java arrays regex string hashmap

我正在研究一个问题,我必须根据以下条件从一堆测试结果中计算平均值。 -他的程序已在多个测试用例上进行了测试,每个测试用例均具有以下结果:“确定”,“答案错误”,“超时”,“运行时错误” -测试用例按连续自然数编号 -仅当该组中每个测试用例的结果为“ OK”时,他的程序才为该组得分 例如,如果测试用例名称为test1,test2a,test2b,test2c,test3,test4。在这种情况下,test2a,test2b,test2c都组成一个小组,并且必须都获得OK才能获得一个总分。

编写函数

class Solution{
public int solution (String[] test, String[] result){}
}
//example:
test[0] = "test1a",  result[0] = "Wrong answer"
test[1] = "test2",  result[1] = "OK"
test[2] = "test1b",  result[2] = "Runtime error"
test[3] = "test1c",  result[0] = "OK"
test[4] = "test3",  result[4] = "Time limit exceeded" 
//result above is 33.

假设整数在1-300范围内 -数组测试和结果的长度相同 -每个测试用例仅出现一次 -test用例按从1开始的连续自然整数排序。 包含至少两个测试的组中的-test用例由字母a的小写后缀与a区分。 -结果中的每个字符串都包含“确定”,“错误答案”,“超时”,“运行时错误”之一

现在,我编写了代码来剥离测试String数组,并获取每个测试组的整数。然后,我创建了一个Integer HashMap Integer,在其中检查使用正则表达式后收集的整数,并在为它们分配100之前检查以确保组中的所有测试用例都是“ OK”。

import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int solution(String[] test, String[] result)
{
    HashMap<Integer, Integer> scoreMap =  new HashMap<Integer, Integer>();

    int[] stripped = new int[test.length];

    //stripped the String of numbers..
    for(int i = 0; i < test.length;i++)
    {
       stripped[i] = Integer.parseInt(test[i].replaceAll("[^0-9]", ""));
    }

    //working with just the numbers from the test groups array
    for(int i = 0; i < stripped.length; i++)
    {
        if(scoreMap.containsKey(stripped[i]))
        {
            if(result[i].equals("OK"))
                scoreMap.put(stripped[i], 100);

            else
                scoreMap.put(stripped[i], 0);
        }

        else
        {
            if(result[i].equals("OK"))
                scoreMap.put(stripped[i], 100);

            else
                scoreMap.put(stripped[i], 0);
        }

    }

    int correctAnswers = 0;
    for(int val: scoreMap.values())
    {
        if(val == 100)
            correctAnswers++;
    }

    double avg =  correctAnswers/scoreMap.size() * 100;

    return (int)Math.floor(avg); 

    //return Math.floor(correctAnswers/scoreMap.size() * 100);

}


public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
    String[] test1 = {"test1", "test2a", "test2b", "test4", "test2c", "test3", "test5", "test6", "test7"};
    String[] results1 = {"OK", "OK", "Wrong answer", "OK", "Wrong answer", "Wrong answer", "OK", "TimeOut","Runtime error"}; 
    int average1 =  solution(test1, results1);

    String[] test2 = {"stackoverflow1", "stackoverflow2a", "stackoverflow2b", "stackoverflow4", "stackoverflow2c", "stackoverflow3", "stackoverflow5", "stackoverflow6", "stackoverflow7"};
    String[] results2 = {"Runtime error", "OK", "Wrong answer", "OK", "TimeOut", "Wrong answer", "OK", "Timeout","TimeOut"};

    int average2 =  solution(test2, results2);

    String[] test3 = {"test1", "test2a", "test2b", "test4", "test2c", "test3", "test5", "test6", "test7"};
    String[] results3 = {"OK", "OK", "TimeOut", "OK", "TimeOut", "OK", "TimeOut", "Runtime error","OK"}; 
    int average3 =  solution(test3, results3);

    System.out.println("Avg1 = " + average1);
    System.out.println("Avg2 = " + average2);
    System.out.println("Avg3 = " + average3);

}

}

2 个答案:

答案 0 :(得分:0)

Well i tried this with Python...

    #!/bin/python3

import math
import os
import random
import re
import sys
# Complete the rotLeft function below.
def rotLeft(T, R):
    my_dict=dict()
    templist=[]
    subgroups=[]
    fianl=0

    for i in range(len(T)):
        my_dict[T[i]]=R[i]

    value=dict()
    for x,y in my_dict.items():
        templist.append(x)


    templist.sort()

    tempgroups= templist[-1]
    if tempgroups[-1].isdigit():
        totalgroups=(int)(tempgroups[-1])
    else:
        totalgroups=(int)(tempgroups[-2])

    for x in templist:
        if x[-1].isdigit():
            continue
        else:
            subgroups.append(x)
    test=""

    i=0
    while i < len(subgroups):
        test=subgroups[i]
        count=0
        totalcount=0
        for item in subgroups:
            if item[-2] == test[-2]:
                totalcount=totalcount+1
            if my_dict[item] == "OK" and item[-2] == test[-2]:
                count = count + 1

        i=i+1
        if totalcount == count:
            fianl=fianl+100 /count


    for x,y in my_dict.items():
        if x[-1].isdigit() and y == "OK":
            fianl=fianl+100


    print ((int)(fianl / totalgroups))








if __name__ == '__main__':
    T = ['test1', 'test3', 'test4', 'test5', 'test5a', 'test5b', 'test6', 'test7a','test7b']
    R = ['Wrong answer', 'OK', 'OK', 'Time limit exceeded', 'OK', 'Wrong answer', 'OK', 'OK','OK']

    result = rotLeft(T, R)

答案 1 :(得分:-1)

如果我对您的理解正确,那么一个测试用例可以包含一个测试或多个测试,正式来讲是一个测试套件。

让我们介绍以下两个类:

private static class TestSuiteResult {
    private String name;
    private List<TestResult> results = new ArrayList<>();

    public TestSuiteResult(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public List<TestResult> getResults() {
        return results;
    }
}

private static class TestResult {
    private String name;
    private String result;

    public TestResult(String name, String result) {
        this.name = name;
        this.result = result;
    }

    public String getName() {
        return name;
    }

    public String getResult() {
        return result;
    }
}

接下来,让我们尝试将输入String[] testsString[] results解析为上述类。 正则表达式test(\d*)([a-z])?匹配以test开头的任何输入,后跟任意数量的数字,并可选地后面跟a-z中的字符。捕获组用于提取所需的片段。

String regex = "(\\w*?)(\\d*)([a-z])?";
Pattern pattern = Pattern.compile(regex);

Map<String, TestResult> testResults = new HashMap<>();
Map<String, TestSuiteResult> testSuiteResults = new HashMap<>();

for (int i = 0; i < tests.length; i++) {

    String test = tests[i];
    Matcher matcher = pattern.matcher(test);

    // check for illegal test name
    if (!matcher.matches()) {
        continue;
    }

    String name = matcher.group(1);
    String digitPart = matcher.group(2);
    String character = matcher.group(3);

    if (character != null) {
        // multi test
        String suiteName = name + digitPart;
        TestSuiteResult suite = testSuiteResults.get(digitPart);
        TestSuiteResult suite = testSuiteResults.get(suiteName);
        if (suite == null) {
            suite = new TestSuiteResult(suiteName);
            testSuiteResults.put(suite.getName(), suite);
        }
        String result = results[i];
        TestResult multi = new TestResult(character, result);
        suite.getResults().add(multi);
    } else {
        // single test
        String result = results[i];
        TestResult single = new TestResult(test, result);
        testResults.put(single.getName(), single);
    }
}

接下来,我们可以从有效测试的总数中计算出测试的总数。我在这里将测试套件视为单个测试,仅在其包含的所有测试均有效时才有效。

int totalAmountOfTests = testResults.size() + testSuiteResults.size();

int validTests = 0;
for (Map.Entry<String, TestResult> entry : testResults.entrySet()) {
    if (entry.getValue().getResult().equals("OK")) {
        validTests++;
    }
}
for (Map.Entry<String, TestSuiteResult> entry : testSuiteResults.entrySet()) {
    List<TestResult> suiteResults = entry.getValue().getResults();
    boolean valid = true;
    for (TestResult suiteResult : suiteResults) {
        if (!suiteResult.getResult().equals("OK")) {
            valid = false;
        }
    }
    if (valid) {
        validTests++;
    }
}

现在,终于可以计算出通过的平均测试量了。将average强制转换为int时,我们将舍入到较低的数字。

double average = (double) totalAmountOfTests / validTests;
int averageRounded = (int) average;

here中提供了完整的有效示例。