Question

image.png
image.png

give code in c++

Réflexion

Interpreting coding challenge from image

The task is to provide a C++ solution for a problem based on an image. The problem involves mapping letters ('a' to 'h') to numeric combinations and generating a 2D array containing all possible combinations. The image text includes a string and a mapping for each letter, so I’ll focus on parsing and formulating the C++ code based on that.

Thought for 28s

Réponse

Use this C++ code for the function:

cpp
#include <bits/stdc++.h> using namespace std; int wasteOfTime(string input1) { const long long MOD = 1000000007LL; // count of mapped numbers for each character // a->[1,2], b->[3,4], c->[5,6], d->[7,8], // e->[9,10,11], f->[12,13], g->[14,15], h->[16] vector<long long> cnt = {2, 2, 2, 2, 3, 2, 2, 1}; // sum of mapped numbers for each character vector<long long> sum = {3, 7, 11, 15, 30, 25, 29, 16}; int n = input1.size(); vector<long long> prefix(n + 1, 1), suffix(n + 1, 1); // prefix product of counts for (int i = 0; i < n; i++) { int idx = input1[i] - 'a'; prefix[i + 1] = (prefix[i] * cnt[idx]) % MOD; } // suffix product of counts for (int i = n - 1; i >= 0; i--) { int idx = input1[i] - 'a'; suffix[i] = (suffix[i + 1] * cnt[idx]) % MOD; } long long ans = 0; // contribution of each position for (int i = 0; i < n; i++) { int idx = input1[i] - 'a'; // number of combinations for all other positions long long ways = (prefix[i] * suffix[i + 1]) % MOD; // add contribution of current position ans = (ans + (sum[idx] * ways) % MOD) % MOD; } return (int)ans; }

For input1 = "ade", this returns 228.

The idea is: each character contributes its mapped-number sum multiplied by the number of combinations possible at all other positions.

Partager cette Q&R