हमें कैरेक्टर्स की एक स्ट्रिंग दी गई है और कार्य है उन कैरेक्टर जोड़ों की संख्या गिनना जिनके बीच की दूरी अंग्रेजी वर्णमाला में उनकी दूरी के बराबर है।
इनपुट - string str = "Tutorials Point"
आउटपुट - अंग्रेजी वर्णमाला के समान दूरी पर कैरेक्टर जोड़ों की संख्या: 5
व्याख्या - समान दूरी वाले जोड़े हैं: (u,t), (u,r), (t,r), (i,o), (s,n)। कुल 5 जोड़े।
उपयोग किया गया दृष्टिकोण
- स्ट्रिंग इनपुट करें और फंक्शन में पास करें।
countवेरिएबल लें।- स्ट्रिंग की लंबाई ज्ञात करें।
- दो नेस्टेड लूप: i = 0 से len-1, j = i+1 से len-1 तक।
temp = abs(str[i] - str[j])सेट करें।- यदि
temp == abs(i - j)तोcount++करें। - काउंट वापस करें और प्रिंट करें।
उदाहरण (C++ कोड)
#include <bits/stdc++.h>
using namespace std;
int pairs_distance(string str) {
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
int temp = abs(str[i] - str[j]);
if (temp == abs(i - j))
count++;
}
}
return count;
}
int main() {
string str = "Tutorials Point";
cout << "Count of character pairs at same distance as in English alphabets are: " << pairs_distance(str);
return 0;
} आउटपुट
Count of character pairs at same distance as in English alphabets are: 5