Advertisement
nocturnalmk

Untitled

Nov 24th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package aud6zad8;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import java.util.ListIterator;
  7.  
  8. public class LuckySuitor {
  9.  
  10.     public static final int RIGHT = 1; // --->
  11.     public static final int LEFT = -1; // <---
  12.  
  13.     public static int whoIsLucky(int n) {
  14.  
  15.         List<Integer> positions = new ArrayList<Integer>();
  16.  
  17.         for (int i = 1; i <= n; i++) {
  18.             positions.add(i);
  19.         }
  20.  
  21.         ListIterator<Integer> it = positions.listIterator();
  22.         printList(positions);
  23.  
  24.         while (true) {
  25.  
  26.             int dir = RIGHT;
  27.             int count = 0;
  28.  
  29.             while (it.hasNext() && dir == RIGHT) {
  30.                 it.next();
  31.                 count++;
  32.                 if (count == 3) {
  33.                     count = 0;
  34.                     it.remove();
  35.                     printList(positions);
  36.                 }
  37.  
  38.                 if (!it.hasNext()) {
  39.                     it.previous();
  40.                     dir = LEFT;
  41.                     break;
  42.                 }
  43.             }
  44.  
  45.             while (it.hasPrevious() && dir == LEFT) {
  46.                 count++;
  47.                 it.previous();
  48.                 if (count == 3) {
  49.                     count = 0;
  50.                     it.remove();
  51.                     printList(positions);
  52.                 }
  53.  
  54.                 if (!it.hasPrevious()) {
  55.                     it.next();
  56.                     dir = RIGHT;
  57.                     break;
  58.                 }
  59.                
  60.             }
  61.            
  62.             if (positions.size() == 1) {
  63.                 break;
  64.             }
  65.  
  66.         }
  67.  
  68.         return 0;
  69.     }
  70.  
  71.     public static void printList(List<Integer> list) {
  72.         Iterator<Integer> it = list.iterator();
  73.  
  74.         while (it.hasNext()) {
  75.             System.out.print(it.next() + " ");
  76.         }
  77.         System.out.println();
  78.     }
  79.  
  80.     public static void main(String[] args) {
  81.         System.out.println("\n\n" + whoIsLucky(5));
  82.     }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement