【华为OD机试】报数游戏(约瑟夫环算法解题—Java&Python&C++&JS实现)
以下是使用Java、Python、C++和JavaScript实现的约瑟夫环算法的代码示例:
Java版本:
public class JosephusGame {
public static void josephusGame(int n, int k) {
LinkedList<Integer> circle = new LinkedList<>();
for (int i = 1; i <= n; i++) {
circle.add(i);
}
int idx = 0;
while (circle.size() > 1) {
idx = (idx + k - 1) % circle.size();
circle.remove(idx);
}
System.out.println("最后剩下的人是:" + circle.get(0));
}
public static void main(String[] args) {
josephusGame(5, 3); // 例如,n = 5,k = 3的情况
}
}
Python版本:
class JosephusGame:
def josephus_game(self, n, k):
circle = list(range(1, n + 1))
while len(circle) > 1:
idx = (idx + k - 1) % len(circle)
del circle[idx]
print(f"最后剩下的人是:{circle[0]}")
jg = JosephusGame()
jg.josephus_game(5, 3) # 例如,n = 5,k = 3的情况
C++版本:
#include <iostream>
#include <list>
void josephusGame(int n, int k) {
std::list<int> circle(n);
std::iota(circle.begin(), circle.end(), 1);
auto it = circle.begin();
while (circle.size() > 1) {
for (int i = 0; i < k - 1; ++i) {
++it;
if (it == circle.end()) {
it = circle.begin();
}
}
auto next_it = ++it;
if (next_it == circle.end()) {
next_it = circle.begin();
}
circle.erase(it);
it = next_it;
}
std::cout << "最后剩下的人是:" << *it << std::endl;
}
int main() {
josephusGame(5, 3); // 例如,n = 5,k = 3的情况
return 0;
}
JavaScript版本:
function josephusGame(n, k) {
let circle = Array.from({ length: n }, (_, i) => i + 1);
let idx = 0;
while (circle.length > 1) {
idx = (idx + k - 1) % circle.length;
circle.splice(idx, 1);
}
console.log(`最后剩下的人是:${circle[0]}`);
}
josephusGame(5, 3); // 例如,n = 5,k = 3的情况
以上代码实现了约瑟夫环的核心功能,并在主函数中提供了使用例子。
评论已关闭