检查数组中给定的K元素

时间:2019-04-26 20:03:25

标签: c++ algorithm

这项作业是关于在湖上进行的赛船比赛。

我有一个N数组,在其中输入风速。 我必须给出一个K数,该数字确定连续多少天风速在10到100之间。 如果我发现K个连续元素的数量,则必须安慰掉该序列的第一个元素的索引。

目标是找到开始“比赛”的日期。

例如:

export const fetchCurrentUserEpic = (action$, state$) => {
  const requestType = FETCH_CURRENT_USER;
  const successType = RECEIVE_CURRENT_USER;
  const requestConfig = {
    url: "/current_user",
    method: "get",
  }
  const payload = {requestConfig, requestType, successType};
  const payloadNormalizer = ({response}) => {
    return {currentUser: response.data.data};
  }

  return action$.ofType(FETCH_CURRENT_USER).pipe(
    switchMap((action) => of({
      type: CALL_API,
      payload: {...payload, requestId: action.requestId, shouldFail: action.shouldFail, payloadNormalizer},
    })),
  )
}

export const apiEpic = (action$, state$) => {
  return action$.ofType(CALL_API).pipe(
    mergeMap((action) => (
      concat(
        of({type: REQ_START, payload: {requestId: action.payload.requestId, requestType: action.payload.requestType}}),
        from(callApi(action.payload.requestConfig, action.payload.shouldFail)).pipe(
            map(response => {
              return {
                type: action.payload.successType,
                payload: action.payload.payloadNormalizer({response})
              }
            }),
            map(() => {
              return {
                type: REQ_END,
                payload: {status: 'success', requestId: action.payload.requestId, requestType: action.payload.requestType},
              }
           })
          )
        )
      ).pipe(
        catchError(error => {
          console.log('error', error);
          return of({type: REQ_END, payload: {status: 'failed', requestId: action.payload.requestId, requestType: action.payload.requestType}, error});
        })
      )
    )
  )
}

输出必须为6,因为它是该序列开始的数组的第6个元素。

我不知道如何进行这项检查。

我尝试过:

S[10] = {50,40,0,5,0,80,70,90,100,120}
K=3

但是我意识到K可以是任何数字,因此我必须立即检查K个元素。

2 个答案:

答案 0 :(得分:0)

您需要具有一个初始设置为0的计数器变量,以及另一个用于存储序列开始位置的索引的变量。并一次遍历数组一个元素。如果找到介于10到100之间的元素,请检查计数器是否等于'0'。如果是,请将索引存储在另一个变量中。计数器加一。如果计数器等于K,那么您就完成了,因此请break从循环开始。否则,如果元素不在10到100之间,则将计数器设置为0

答案 1 :(得分:0)

使用算法标准库

(限制:以下答案提供了一种对C ++ 17及更高版本有效的方法)

对于这样的问题,您可能需要考虑使用algorithms library in the standard librarystd::transform转向std::search_n,而不是重新发明轮子, >

  • 在风速上产生integer -> bool转换为所述风速的有效性,然后
  • 在转换结果中搜索多个(K之后的true(有效风速)元素,

分别。

例如:

#include <algorithm>  // std::search_n, std::transform
#include <cstdint>    // uint8_t (for wind speeds)
#include <iostream>   // std::cout
#include <iterator>   // std::back_inserter, std::distance
#include <vector>     // std::vector

int main() {
  // Wind data and wind restrictions.
  const std::vector<uint8_t> wind_speed{50U, 40U, 0U,  5U,   0U,
                                        80U, 70U, 90U, 100U, 120U};
  const uint8_t minimum_wind_speed = 10U;
  const uint8_t maximum_wind_speed = 100U;
  const std::size_t minimum_consecutive_days = 3;

  // Map wind speeds -> wind speed within limits.
  std::vector<bool> wind_within_limits;
  std::transform(wind_speed.begin(), wind_speed.end(),
                 std::back_inserter(wind_within_limits),
                 [](uint8_t wind_speed) -> bool {
                   return (wind_speed >= minimum_wind_speed) &&
                          (wind_speed <= maximum_wind_speed);
                 });

  // Find the first K (minimum_consecutive_days) consecutive days with
  // wind speed within limits.
  const auto starting_day =
      std::search_n(wind_within_limits.begin(), wind_within_limits.end(),
                    minimum_consecutive_days, true);
  if (starting_day != wind_within_limits.end()) {
    std::cout << "Race may start at day "
              << std::distance(wind_within_limits.begin(), starting_day) + 1
              << ".";
  } else {
    std::cout
        << "Wind speeds during the specified days exceed race conditions.";
  }
}

或者,我们可以在std::search_n调用中将转换集成到二进制谓词中。这样会产生一个更紧凑的解决方案,但在imo上,语义和可读性会更差。

#include <algorithm>  // std::search_n
#include <cstdint>    // uint8_t (for wind speeds)
#include <iostream>   // std::cout
#include <iterator>   // std::distance
#include <vector>     // std::vector

int main() {
  // Wind data and wind restrictions.
  const std::vector<uint8_t> wind_speed{50U, 40U, 0U,  5U,   0U,
                                        80U, 70U, 90U, 100U, 120U};
  const uint8_t minimum_wind_speed = 10U;
  const uint8_t maximum_wind_speed = 100U;
  const std::size_t minimum_consecutive_days = 3;

  // Find any K (minimum_consecutive_days) consecutive days with wind speed
  // within limits.
  const auto starting_day = std::search_n(
      wind_speed.begin(), wind_speed.end(), minimum_consecutive_days, true,
      [](uint8_t wind_speed, bool) -> bool {
        return (wind_speed >= minimum_wind_speed) &&
               (wind_speed <= maximum_wind_speed);
      });
  if (starting_day != wind_speed.end()) {
    std::cout << "Race may start at day "
              << std::distance(wind_speed.begin(), starting_day) + 1 << ".";
  } else {
    std::cout
        << "Wind speeds during the specified days exceed race conditions.";
  }
}

鉴于您提供的特定(硬编码)风力数据和限制,上述两个程序均导致:

Race may start at day 6.