AlbertMourato

Q-Algorithm

May 3rd, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3.  
  4. public class QAlgorithm {
  5.  
  6.     public static int[] tagRN;
  7.     public static int[] tagReaderRN;
  8.  
  9.     public static boolean allMarked(int[] array) {
  10.         for (int i = 0; i < array.length; i++) {
  11.             if (array[i] != -1)
  12.                 return false;
  13.         }
  14.         return true;
  15.     }
  16.  
  17.     // return all index that has 0 as Reader Random Number
  18.     public static String getZeroIndex(int[] array) {
  19.         String s = "";
  20.         for (int i = 0; i < array.length; i++) {
  21.             if (array[i] == 0)
  22.                 s += i;
  23.         }
  24.         return s;
  25.     }
  26.    
  27.     public static void decrease(int[] array){
  28.         for (int i = 0; i < array.length; i++) {
  29.             array[i]--;
  30.         }
  31.     }
  32.  
  33.     public static void qAlgorithm(int q, int numberOfTags) {
  34.         Random random = new Random();
  35.         // reader ask the tags to generate two random numbers
  36.         tagRN = new int[numberOfTags];// RN that identify each tag
  37.         tagReaderRN = new int[numberOfTags]; // RN that is used by reader to choose which of them will be chosen
  38.        
  39.         for (int i = 0; i < numberOfTags; i++) {
  40.             tagRN[i] = random.nextInt(65535); //give all tag a "id" number that wasn't used
  41.             tagReaderRN[i] = random.nextInt(((int) Math.pow(2, q)) - 1);//give all tag a RN 0-(2^q -1)
  42.         }
  43.         while (!allMarked(tagReaderRN)) {
  44.             // now, ask if any tag chose 0 as its second random number
  45.             int t = getZeroIndex(tagReaderRN).length();
  46.             if (t > 1) {
  47.                 for (int i = 0; i < t; i++) {//if more than 1 tag has 0 as RRN, we choose another RRN
  48.                     tagReaderRN[getZeroIndex(tagReaderRN).charAt(i) - '0'] = random.nextInt(((int) Math.pow(2, q)) - 1);
  49.                 }
  50.             } else if (t == 1) {
  51.                 tagReaderRN[getZeroIndex(tagReaderRN).charAt(0)] = -1;//tag is marked as read
  52.             }else{
  53.                 decrease(tagReaderRN); //no tag has 0 as ReaderRN
  54.             }
  55.         }
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment