Advertisement
ingwey

sdfac

Apr 12th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. //Josephus.java
  2.  
  3. //Out of n members, every m'th person will be eliminated
  4. import java.io.*;
  5.  
  6. //Stack---------------
  7. class Node<T> {
  8.  
  9. T value;
  10. Node<T> link;
  11. }
  12.  
  13. class Stack<T> {
  14.  
  15. Node<T> top;
  16.  
  17. public Stack() {
  18. top = null;
  19. }
  20.  
  21. public void push(T item) {
  22. Node<T> n = new Node<T>();
  23. n.value = item;
  24. n.link = top;
  25. top = n;
  26. }
  27.  
  28. public T pop() {
  29. T item;
  30. item = top.value;
  31. Node<T> n = top;
  32. n = null;
  33. top = top.link;
  34. return item;
  35. }
  36.  
  37. public void display() {
  38. Node<T> n = top;
  39. System.out.print("(top)");
  40. while (n != null) {
  41. System.out.print(" ->" + n.value);
  42. n = n.link;
  43. }
  44. System.out.println();
  45. }
  46. }
  47.  
  48. //Queue---------------------------
  49. class Queue<T> {
  50.  
  51. Node<T> front, rear;
  52. Stack<T> s1 = new Stack<T>();
  53. Stack<T> s2 = new Stack<T>();
  54.  
  55. public Queue() {
  56. }
  57.  
  58. public void add(T item) {
  59. while (s2.top != null) {
  60. s1.push(s2.pop());
  61. }
  62. s1.push(item);
  63. rear = s1.top;
  64. while (s1.top != null) {
  65. s2.push(s1.pop());
  66. }
  67. front = s2.top;
  68. }
  69.  
  70. public T remove() {
  71. T item = s2.pop();
  72. front = s2.top;
  73. return item;
  74. }
  75.  
  76. public void display() {
  77. Node<T> n = s2.top;
  78. System.out.print("(front)");
  79. while (n != null) {
  80. System.out.print(" <-" + n.value);
  81. n = n.link;
  82. }
  83. System.out.println(" <-(rear)");
  84. }
  85. }
  86.  
  87. //Josephus Problem-------------------
  88. public class Josephus {
  89.  
  90. public static void main(String[] args) throws IOException {
  91. Queue<Integer> q = new Queue<Integer>();
  92. Queue<Integer> q1 = new Queue<Integer>();
  93. int n, m, i;
  94. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  95. System.out.println("Enter no. of members (n) : ");
  96. n = 13;
  97. System.out.println("Enter the elimination number (m) : ");
  98. m = 7;
  99. for (i = 1; i <= n; i++) {
  100. q.add(i);
  101. }
  102.  
  103. Node<Integer> node = q.front;
  104. int l, k = 0;
  105. while (k != n - 1) {
  106. for (i = 1; i < m; i++) {
  107. q.add(q.remove());
  108. }
  109. l = q.remove();
  110. q1.add(l);
  111. k++;
  112. }
  113. System.out.println("Order of elimination is : ");
  114. while (q1.front != null) {
  115. System.out.print(q1.remove() + ",");
  116. }
  117. System.out.println("nWinner is : " + q.remove());
  118. }
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement