สมมติว่าเราได้รับตัวเลข k สองตัว m และ n ตัวเลขของตัวเลขจะถูกสุ่มแบบสุ่มแล้วเปรียบเทียบ เราต้องหาว่าเลขใดมีความเป็นไปได้สูงที่จะมากกว่า
ดังนั้น หากอินพุตเป็น n =231, m =337, k =3 ผลลัพธ์จะเป็น 'Second' หรือตัวเลขที่สองมีโอกาสสูงกว่าที่จะมากกว่า
ขั้นตอน
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
s1 := convert n to string
s2 := convert m to string
f := 0, s = 0
for initialize i := 0, when i < k, update (increase i by 1), do:
if s1[i] > s2[i], then:
(increase f by 1)
otherwise when s1[i] < s2[i], then:
(increase s by 1)
if f > s, then:
print("First")
otherwise when s > f, then:
print("Second")
Otherwise
print("Equal") ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, int m, int k) {
string s1 = to_string(n);
string s2 = to_string(m);
int f = 0, s = 0;
for(int i = 0; i < k; i++){
if(s1[i] > s2[i])
f++;
else if(s1[i] < s2[i])
s++;
}
if(f > s)
cout<<"First"<<endl;
else if(s > f)
cout<<"Second"<<endl;
else
cout<<"Equal"<<endl;
}
int main() {
int n = 231, m = 337, k = 3;
solve(n, m, k);
return 0;
} อินพุต
231, 337, 3
ผลลัพธ์
Second