AlbertMourato

Untitled

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