Ejemplo n.º 1
0
  public static void recSort(ArrayList<Integer> arr, int left, int right) {

    if (left >= right) return;

    int mid = (left + right) / 2;

    recSort(arr, left, mid);
    recSort(arr, mid + 1, right);

    // combine

    ArrayList<Integer> copy = new ArrayList<Integer>();

    // MERGE
    int a = left;
    int b = mid + 1;

    while (a <= mid && b <= right) {
      int cmp;
      cmp = arr.get(a) - arr.get(b);

      if (cmp < 0) copy.add(arr.get(a++));
      else copy.add(arr.get(b++));
    }

    while (a <= mid) copy.add(arr.get(a++));
    while (b <= right) copy.add(arr.get(b++));

    // Put back
    int c = 0;
    for (int i = left; i <= right; i++) arr.set(i, copy.get(c++));
  }
  private MockTelemetryModule generateTelemetryModules(boolean addParameter) {
    AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false);
    ApplicationInsightsXmlConfiguration appConf = mockParser.build(null);
    appConf.setInstrumentationKey(MOCK_IKEY);

    TelemetryModulesXmlElement modulesXmlElement = new TelemetryModulesXmlElement();
    ArrayList<AddTypeXmlElement> modules = new ArrayList<AddTypeXmlElement>();
    AddTypeXmlElement addXmlElement = new AddTypeXmlElement();
    addXmlElement.setType("com.microsoft.applicationinsights.internal.config.MockTelemetryModule");

    if (addParameter) {
      final ParamXmlElement param1 = new ParamXmlElement();
      param1.setName("param1");
      param1.setValue("value1");

      ArrayList<ParamXmlElement> list = new ArrayList<ParamXmlElement>();
      list.add(param1);

      addXmlElement.setParameters(list);
    }

    modules.add(addXmlElement);
    modulesXmlElement.setAdds(modules);
    appConf.setModules(modulesXmlElement);

    TelemetryConfiguration mockConfiguration = new TelemetryConfiguration();

    initializeWithFactory(mockParser, mockConfiguration);

    MockTelemetryModule module =
        (MockTelemetryModule) mockConfiguration.getTelemetryModules().get(0);

    return module;
  }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
  @SuppressWarnings("unchecked")
  @Override
  public List<Version> getVersions() {
    if (versions == null) {
      int count = 1;

      if (revisions != null) {
        count = count + revisions.size();
      }

      ArrayList<Version> list = new ArrayList<>(count);

      if (getTime() != Long.MIN_VALUE) {
        list.add(new Version(this));
      }

      if (revisions != null) {
        for (LongRevision lr : revisions) {
          if (lr.getTime() != Long.MIN_VALUE) {
            list.add(new Version(lr));
          }
        }
      }

      versions = list;
    }

    return (List<Version>) versions;
  }
Ejemplo n.º 5
0
  public MoquiStart(ClassLoader parent, boolean loadWebInf) {
    super(parent);
    this.loadWebInf = loadWebInf;

    URL wrapperWarUrl = null;
    try {
      // get outer file (the war file)
      pd = getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      wrapperWarUrl = cs.getLocation();
      outerFile = new JarFile(new File(wrapperWarUrl.toURI()));

      // allow for classes in the outerFile as well
      jarFileList.add(outerFile);

      Enumeration<JarEntry> jarEntries = outerFile.entries();
      while (jarEntries.hasMoreElements()) {
        JarEntry je = jarEntries.nextElement();
        if (je.isDirectory()) continue;
        // if we aren't loading the WEB-INF files and it is one, skip it
        if (!loadWebInf && je.getName().startsWith("WEB-INF")) continue;
        // get jars, can be anywhere in the file
        String jeName = je.getName().toLowerCase();
        if (jeName.lastIndexOf(".jar") == jeName.length() - 4) {
          File file = createTempFile(je);
          jarFileList.add(new JarFile(file));
        }
      }
    } catch (Exception e) {
      System.out.println("Error loading jars in war file [" + wrapperWarUrl + "]: " + e.toString());
    }
  }
Ejemplo n.º 6
0
  public void addProgress(@NotNull ProgressIndicatorEx original, @NotNull TaskInfo info) {
    synchronized (myOriginals) {
      final boolean veryFirst = !hasProgressIndicators();

      myOriginals.add(original);
      myInfos.add(info);

      final InlineProgressIndicator expanded = createInlineDelegate(info, original, false);
      final InlineProgressIndicator compact = createInlineDelegate(info, original, true);

      myPopup.addIndicator(expanded);
      myProgressIcon.resume();

      if (veryFirst && !myPopup.isShowing()) {
        buildInInlineIndicator(compact);
      } else {
        buildInProcessCount();
        if (myInfos.size() > 1 && Registry.is("ide.windowSystem.autoShowProcessPopup")) {
          openProcessPopup(false);
        }
      }

      runQuery();
    }
  }
Ejemplo n.º 7
0
  private Collection<Modifier> generateModifiers(int modifiers) {
    ArrayList<Modifier> mods = new ArrayList<Modifier>();

    // first, protection modifiers
    switch (modifiers & WyilFileWriter.MODIFIER_PROTECTION_MASK) {
      case WyilFileWriter.MODIFIER_Public:
        mods.add(Modifier.PUBLIC);
        break;
      case WyilFileWriter.MODIFIER_Protected:
        mods.add(Modifier.PROTECTED);
        break;
      case WyilFileWriter.MODIFIER_Private:
        mods.add(Modifier.PRIVATE);
        break;
      default:
        throw new RuntimeException("Unknown modifier");
    }

    // second, mangle modifiers
    switch (modifiers & WyilFileWriter.MODIFIER_MANGLE_MASK) {
      case WyilFileWriter.MODIFIER_Native:
        mods.add(Modifier.NATIVE);
        break;
      case WyilFileWriter.MODIFIER_Export:
        mods.add(Modifier.EXPORT);
        break;
    }

    return mods;
  }
Ejemplo n.º 8
0
 public static List<AttrPack> expand(AttrPack attr) {
   char node_type_list[] = new char[4];
   List<Integer> rimo_path = getRightMostPath(attr.getPath());
   // List<Integer> rimo_path = getRightMostPath(debug);
   // List<Tuple> cand = rightMostExpand(debug);
   List<Tuple> cand = rightMostExpand(attr.getPath());
   char[] path_label = new char[rimo_path.size() + 1];
   int[] path_index = new int[rimo_path.size()];
   for (int i = 0; i < rimo_path.size(); i++) {
     path_index[i] = rimo_path.get(i);
     path_label[i] = attr.getPath().get(path_index[i]).getLabel();
   }
   path_label[rimo_path.size()] = 0;
   List<AttrPack> next_iter = new ArrayList();
   if (attr.getPathIndex() == -1) {
     for (Tuple tup : cand) {
       int d_ = tup.getDepth();
       char l_ = tup.getLabel();
       if (l_ == path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, path_index[d_]));
       }
       if (l_ > path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, -1));
       }
     }
   } else {
     int prefix = attr.getPathIndex() + 1;
     Tuple prf_tup = attr.getPath().get(prefix);
     {
       ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
       tmp_path.add(prf_tup);
       next_iter.add(new AttrPack(tmp_path, prefix));
     }
     for (Tuple tup : cand) {
       int d_ = tup.getDepth();
       char l_ = tup.getLabel();
       if (d_ > prf_tup.getDepth()) {
         continue;
       }
       if (d_ == prf_tup.getDepth() && l_ >= prf_tup.getLabel()) {
         continue;
       }
       if (l_ == path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, path_index[d_]));
       }
       if (l_ > path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, -1));
       }
     }
   }
   return next_iter;
 }
Ejemplo n.º 9
0
  public void updateNodeName(String oldName, String newName) {
    // Update in the whole Tree
    if (!oldName.isEmpty() && !newName.isEmpty()) {

      Enumeration en = root.depthFirstEnumeration();

      while (en.hasMoreElements()) {
        DecisionTreeNode node = (DecisionTreeNode) en.nextElement();
        if (node.nodeName.compareTo(oldName) == 0) {
          node.nodeName = newName;
        }
      }
    }

    // Update in the added Node List
    ArrayList<String> nodesToBeAdded = new ArrayList<String>(addedNodes);
    addedNodes.clear();

    for (String node : nodesToBeAdded) {
      String[] arr = node.split(":");
      if (arr[1].compareTo(oldName) == 0) {
        addedNodes.add(arr[0] + ":" + newName + ":" + arr[2]);
      } else {
        addedNodes.add(node);
      }
    }

    // Update in the correctNode list
    correctNodes.put(newName, correctNodes.get(oldName));
    correctNodes.remove(oldName);
  }
 public ArrayList<String> letterCombinations(String digits) {
   // Start typing your Java solution below
   // DO NOT write main() function
   /*
   brillant idea to store those values into string
   */
   String[] arrays = new String[10];
   arrays[2] = "abc";
   arrays[3] = "def";
   arrays[4] = "ghi";
   arrays[5] = "jkl";
   arrays[6] = "mno";
   arrays[7] = "pqrs";
   arrays[8] = "tuv";
   arrays[9] = "wxyz";
   ArrayList<String> result = new ArrayList<String>();
   result.add("");
   if (digits.length() == 0) return result;
   for (int i = 0; i < digits.length(); i++) {
     String num = arrays[digits.charAt(i) - '0'];
     ArrayList<String> tempResult = new ArrayList<String>();
     for (String s : result) {
       for (int j = 0; j < num.length(); j++) {
         tempResult.add(s + num.charAt(j));
       }
     }
     result = tempResult;
   }
   return result;
 }
Ejemplo n.º 11
0
  // TODO Check https://leetcode.com/discuss/58149/my-simple-java-solution
  public int[] plusOne(int[] digits) {
    if (digits == null || digits.length == 0) return digits;

    ArrayList<Integer> list = new ArrayList<Integer>();

    int elementToAdd = 1;
    for (int i = digits.length - 1; i >= 0; i--) {
      int newElem = digits[i] + elementToAdd;

      elementToAdd = 0;
      if (newElem > 9) {
        elementToAdd = 1;
        newElem = 0;
      }
      list.add(newElem);
    }

    if (elementToAdd == 1) {
      list.add(elementToAdd);
    }

    int[] result = new int[list.size()];

    for (int i = 0; i < list.size(); i++) {
      result[list.size() - i - 1] = list.get(i);
    }

    return result;
  }
Ejemplo n.º 12
0
    /**
     * Return true if all predicate tests on a certain resource entry evaluate to true
     *
     * @param resource the resource
     * @param allowListMatch if true, allow the test to be a list of strings
     * @param predicateTransformer a Converter<S,Predicate> to convert String to Predicate test
     * @param key the resource attribute key to check
     * @param test test to apply, can be a String, or List of Strings if allowListMatch is true
     */
    boolean applyTest(
        final Map<String, String> resource,
        final boolean allowListMatch,
        final Converter<String, Predicate> predicateTransformer,
        final String key,
        final Object test) {

      final ArrayList<Predicate> tests = new ArrayList<Predicate>();
      if (allowListMatch && test instanceof List) {
        // must match all values
        for (final Object item : (List) test) {
          final String s = (String) item;
          tests.add(predicateTransformer.convert(s));
        }
      } else if (test instanceof String) {
        // match single test
        tests.add(predicateTransformer.convert((String) test));
      } else {
        // unexpected format, do not match
        logger.error(
            identify() + ": cannot evaluate unexpected type: " + test.getClass().getName());
        return false;
      }

      return PredicateUtils.allPredicate(tests).evaluate(resource.get(key));
    }
 public boolean comparePrefix(String prefixCode, String prefixCodeWithProc) {
   try {
     boolean flag = false;
     String prefixBreak[] = prefixCode.split("#");
     String prefixProcBreak[] = prefixCodeWithProc.split("#");
     for (String str : prefixBreak) {
       flag = false;
       for (int i = 0; i < prefixProcBreak.length; i++) {
         if (prefixProcBreak[i].equals(str)) {
           flag = true;
           prefixProcBreak[i] = "-1";
           break;
         }
       }
       if (!flag) return false;
     }
     if (prefixCode.length() == prefixCodeWithProc.length()) {
       procList.clear();
       procList.add(prefixCodeWithProc);
       return true;
     } else procList.add(prefixCodeWithProc);
   } catch (Exception ed) {
   }
   return false;
 }
Ejemplo n.º 14
0
  public static void main(String[] args) {
    FileSystemNode d1, d2, d3, d4;
    ArrayList<FileSystemNode> l1, l2;
    d1 = new FileNode("opg87", 120);
    assert d1.accept(new SizeVisitor()) == 120;
    d2 = new FileNode("opg14", 125);
    l1 = new ArrayList<FileSystemNode>();
    l1.add(d1);
    l1.add(d2);
    d3 = new DirectoryNode("obl", l1);
    assert d3.accept(new SizeVisitor()) == 245;
    d4 = new DirectoryNode("B-opgaver", new ArrayList<FileSystemNode>());
    assert d4.accept(new SizeVisitor()) == 0;
    l2 = new ArrayList<FileSystemNode>();
    l2.add(d3);
    l2.add(d4);
    d3 = new DirectoryNode("dprog2", l2);

    // d3.accept(new ListFileSizeVisitor());
    // d3.accept(new SearchVisitor("opg"));

    try {
      assert false;
      System.out.println("Please enable assertions!");
    } catch (AssertionError e) {
      System.out.println("Success!");
    }
  }
Ejemplo n.º 15
0
  private void handleNewExternalTransactionsInt(Collection<TransactionEx> transactions)
      throws WapiException {
    // Transform and put into two arrays with matching indexes
    ArrayList<TransactionEx> texArray = new ArrayList<TransactionEx>(transactions.size());
    ArrayList<Transaction> txArray = new ArrayList<Transaction>(transactions.size());
    for (TransactionEx tex : transactions) {
      try {
        txArray.add(Transaction.fromByteReader(new ByteReader(tex.binary)));
        texArray.add(tex);
      } catch (TransactionParsingException e) {
        // We hit a transaction that we cannot parse. Log but otherwise ignore it
        _logger.logError("Received transaction that we cannot parse: " + tex.txid.toString());
        continue;
      }
    }

    // Grab and handle parent transactions
    fetchStoreAndValidateParentOutputs(txArray);

    // Store transaction locally
    for (int i = 0; i < txArray.size(); i++) {
      _backing.putTransaction(texArray.get(i));
      onNewTransaction(texArray.get(i), txArray.get(i));
    }
  }
Ejemplo n.º 16
0
  public WDBObject[] search(SimpleNode expression, Adapter scda) throws Exception {
    boolean hasWhereClause = (expression != null);
    WDBObject[] matchesArray = new WDBObject[0];
    ArrayList<WDBObject> matchesList = new ArrayList<WDBObject>();
    WDBObject[] indexFilteredArray;
    if (hasWhereClause) {
      indexFilteredArray =
          expression
              .filterObjectsWithIndexes(scda, this.indexes)
              .getFilteredResults(scda, this.indexes);
    } else {
      indexFilteredArray = null;
    }
    if (indexFilteredArray == null) {
      // Simple for loop for search
      WDBObject object;
      for (int i = 0; i < this.instances.size(); i++) {
        object = this.getInstance(i, scda);
        if (!hasWhereClause || (hasWhereClause && expression.eval(scda, object))) {
          matchesList.add(object);
        }
      }
    } else {
      // Simple for loop for search
      for (int i = 0; i < indexFilteredArray.length; i++) {
        if (!hasWhereClause || (hasWhereClause && expression.eval(scda, indexFilteredArray[i]))) {
          matchesList.add(indexFilteredArray[i]);
        }
      }
    }

    return (WDBObject[]) matchesList.toArray(matchesArray);
  }
Ejemplo n.º 17
0
 public Cube(double x, double y, double z, double w) {
   super();
   id = "Cube";
   width = w;
   ArrayList<Point3D> pts = new ArrayList<Point3D>();
   pts.add(new Point3D(x, y, z));
   pts.add(new Point3D(x + w, y, z));
   pts.add(new Point3D(x + w, y + w, z));
   pts.add(new Point3D(x, y + w, z));
   for (int i = 0; i < pts.size() - 1; i++) {
     lines.add(new Line3D(pts.get(i), pts.get(i + 1)));
   }
   lines.add(new Line3D(pts.get(0), new Point3D(x, y + w, z)));
   int size = lines.size();
   for (int i = 0; i < size; i++) {
     lines.add(
         new Line3D(
             new Point3D(lines.get(i).point1.x, lines.get(i).point1.y, lines.get(i).point1.z + w),
             new Point3D(
                 lines.get(i).point2.x, lines.get(i).point2.y, lines.get(i).point2.z + w)));
   }
   size = pts.size();
   for (int i = 0; i < size; i++) {
     pts.add(new Point3D(pts.get(i).x, pts.get(i).y, pts.get(i).z + w));
   }
   for (int i = 0; i < 4; i++) {
     lines.add(new Line3D(pts.get(i), pts.get(i + 4)));
   }
   pan(new Point3D(0, 0, 0));
 }
Ejemplo n.º 18
0
  /** Gets all permutations of a given word. */
  public ArrayList<String> getPermutations() {
    ArrayList<String> result = new ArrayList<String>();

    // The empty string has a single permutation: itself
    if (word.length() == 0) {
      result.add(word);
      return result;
    }

    // Loop through all character positions
    for (int i = 0; i < word.length(); i++) {
      // Form a simpler word by removing the ith character
      String shorterWord = word.substring(0, i) + word.substring(i + 1);

      // Generate all permutations of the simpler word
      Permutations shorterPermutations = new Permutations(shorterWord);
      ArrayList<String> shorterWordPermutations = shorterPermutations.getPermutations();

      // Add the removed character to the front of
      // each permutation of the simpler word,
      for (String s : shorterWordPermutations) {
        result.add(word.charAt(i) + s);
      }
    }
    // Return all permutations
    return result;
  }
Ejemplo n.º 19
0
  private void marceros(int[] cerodesparej, int[] filnosel) {
    int i, j = cerodesparej[1];
    ArrayList<int[]> secero = new ArrayList<int[]>();
    secero.add(cerodesparej);
    boolean apareao = false;
    do {
      i = colselec[j];
      apareao = -1 != i && secero.add(new int[] {i, j});
      if (!apareao) {
        break;
      }
      j = filnosel[i];
      apareao = -1 != j && secero.add(new int[] {i, j});
    } while (apareao);
    for (int[] zero : secero) {
      if (colselec[zero[1]] == zero[0]) {
        colselec[zero[1]] = -1;
        filselec[zero[0]] = -1;
      }

      if (filnosel[zero[0]] == zero[1]) {
        filselec[zero[0]] = zero[1];
        colselec[zero[1]] = zero[0];
      }
    }
  }
Ejemplo n.º 20
0
 public static void findMaxCut() {
   int arrayCut = Integer.MAX_VALUE;
   int indexCut = Integer.MAX_VALUE;
   int max = Integer.MIN_VALUE;
   int numArrays = occupied.size();
   for (int i = 0; i < numArrays; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len = arr.size();
     for (int j = 0; j < len - 1; j++) {
       if (arr.get(j + 1) - arr.get(j) > max) {
         max = arr.get(j + 1) - arr.get(j);
         indexCut = j;
         arrayCut = i;
       }
     }
   }
   ArrayList<Integer> arr1 = new ArrayList<Integer>();
   ArrayList<Integer> arr2 = new ArrayList<Integer>();
   ArrayList<Integer> arr = occupied.get(arrayCut);
   for (int i = 0; i <= indexCut; i++) {
     arr1.add(arr.get(i));
   }
   for (int i = indexCut + 1; i < arr.size(); i++) {
     arr2.add(arr.get(i));
   }
   occupied.remove(arrayCut);
   occupied.add(arr1);
   occupied.add(arr2);
 }
Ejemplo n.º 21
0
  public static void main(String[] args) throws FileNotFoundException {
    String s;

    ArrayList<String> AL = new ArrayList<String>();
    AL.add("one");
    AL.add("two");
    AL.add("three");
    AL.add("four");
    AL.add("five");
    AL.add("six");
    System.out.println("ArrayList (iterator) " + AL);
    Iterator<String> it = AL.iterator();
    while (it.hasNext()) {
      s = it.next();
      System.out.println("AL: " + s);
    }
    System.out.println();

    myList ml = new myList();
    ml.add(20);
    ml.add(50);
    ml.add(12);
    ml.add(13);
    ml.add(53);
    ml.add(33);
    ml.add(23);

    System.out.println(ml);
    Iterator<Integer> mlit = ml.iterator();
    while (mlit.hasNext()) {
      System.out.println(mlit.next());
    }
  }
  private static CommandLineArgumentsProvider createCommandLineArgumentsProvider(
      final Sdk sdk, final Map<String, String> environmentVariables, int[] ports) {
    final ArrayList<String> args = new ArrayList<String>();
    args.add(sdk.getHomePath());
    final String versionString = sdk.getVersionString();
    if (versionString == null || !versionString.toLowerCase().contains("jython")) {
      args.add("-u");
    }
    args.add(
        FileUtil.toSystemDependentName(PythonHelpersLocator.getHelperPath(PYDEV_PYDEVCONSOLE_PY)));
    for (int port : ports) {
      args.add(String.valueOf(port));
    }
    return new CommandLineArgumentsProvider() {
      @Override
      public String[] getArguments() {
        return ArrayUtil.toStringArray(args);
      }

      @Override
      public boolean passParentEnvs() {
        return false;
      }

      @Override
      public Map<String, String> getAdditionalEnvs() {
        return addDefaultEnvironments(sdk, environmentVariables);
      }
    };
  }
Ejemplo n.º 23
0
  public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    // Start typing your Java solution below
    // DO NOT write main() function

    ArrayList<Interval> res = new ArrayList<Interval>();
    if (intervals.size() == 0) return res;
    Collections.sort(intervals, new MyC());
    int start = 0;
    int end = 0;
    for (int i = 0; i < intervals.size(); i++) {
      if (i == 0) {
        start = intervals.get(i).start;
        end = intervals.get(i).end;
      } else {
        if (intervals.get(i).start <= end) {
          end = Math.max(end, intervals.get(i).end);
        } else {
          res.add(new Interval(start, end));
          start = intervals.get(i).start;
          end = intervals.get(i).end;
        }
      }
    }
    res.add(new Interval(start, end));
    return res;
  }
Ejemplo n.º 24
0
 public void dfs(int v) {
   if (hasCycle) {
     return;
   }
   if (color[v] != 2) {
     color[v] = 1;
     if (graph[v] == null) {
       color[v] = 2;
       answer.add(v);
       return;
     }
     for (int i = 0; i < graph[v].size(); i++) {
       int to = graph[v].get(i);
       if (color[to] == 0) {
         dfs(to);
       }
       if (color[to] == 1) {
         hasCycle = true;
         return;
       }
     }
     color[v] = 2;
     answer.add(v);
   }
 }
    @Override
    public Object findElement(String s) {
      List<ObjectWithWeight> elements = new ArrayList<ObjectWithWeight>();
      s = s.trim();
      final ListIterator<Object> it = getElementIterator(0);
      while (it.hasNext()) {
        final ObjectWithWeight o = new ObjectWithWeight(it.next(), s, getComparator());
        if (!o.weights.isEmpty()) {
          elements.add(o);
        }
      }
      ObjectWithWeight cur = null;
      ArrayList<ObjectWithWeight> current = new ArrayList<ObjectWithWeight>();
      for (ObjectWithWeight element : elements) {
        if (cur == null) {
          cur = element;
          current.add(cur);
          continue;
        }

        final int i = element.compareWith(cur);
        if (i == 0) {
          current.add(element);
        } else if (i < 0) {
          cur = element;
          current.clear();
          current.add(cur);
        }
      }

      return current.isEmpty() ? null : findClosestTo(myInitialPsiElement, current);
    }
Ejemplo n.º 26
0
 /**
  * Given a tissue sample, move all unsatisfied agents to a vacant cell
  *
  * @param tissue a 2-D character array that has been initialized
  * @param threshold the percentage of like agents that must surround the agent to be satisfied
  */
 public static int moveAllUnsatisfied(char[][] tissue, int threshold) {
   ArrayList<Integer> list2 = new ArrayList<Integer>();
   int counter = 0;
   ArrayList<Integer> list1 = new ArrayList<Integer>();
   for (int i = 0; i < tissue.length; i++) {
     for (int x = 0; x < tissue[0].length; x++) {
       if (isSatisfied(tissue, i, x, threshold) == false) {
         list1.add(i);
         list2.add(x);
       }
     }
   }
   int num = list1.size();
   char temp;
   int count = 0;
   do {
     int rand = (int) (Math.random() * tissue.length);
     int random = (int) (Math.random() * tissue.length);
     if (tissue[rand][random] == ' ') {
       temp = tissue[rand][random];
       tissue[rand][random] = tissue[list1.get(counter)][list2.get(counter)];
       tissue[list1.get(counter)][list2.get(counter)] = temp;
       counter++;
       count++;
     }
   } while (counter != num);
   return count;
 }
Ejemplo n.º 27
0
  ArrayList<String> findChunks(String code) throws CompilationException {
    ArrayList<String> chunks = new ArrayList<String>();

    int start = 1;
    while (code.charAt(start) == ' ') start++;

    int end = start;
    while (end < code.length() - 1 && code.charAt(end) != ')') {
      if (code.charAt(start) == '(') {
        end = findClose(code, start);
        chunks.add(code.substring(start, end));
      } else {
        while (code.charAt(end) != ' ' && code.charAt(end) != ')' && code.charAt(end) != '(') {
          end++;
        }

        if (start != end) {
          String chunk = code.substring(start, end);
          chunk = chunk.trim();

          if (!chunk.isEmpty()) chunks.add(chunk);
        }
      }

      while (end < code.length() && code.charAt(end) == ' ') end++;
      start = end;
    }
    if (end != code.length() - 1) throw new CompilationException(code);
    if (code.charAt(0) == '(' && code.charAt(end) != ')') throw new CompilationException(code);

    return chunks;
  }
Ejemplo n.º 28
0
 void $$SINGLETONS() {
   pkgP.init(
       "ti.platforms.evm6424.Package",
       (Proto.Obj) om.findStrict("xdc.IPackage.Module", "ti.platforms.evm6424"));
   pkgP.bind("$capsule", $$UNDEF);
   pkgV.init2(pkgP, "ti.platforms.evm6424", Value.DEFAULT, false);
   pkgV.bind("$name", "ti.platforms.evm6424");
   pkgV.bind("$category", "Package");
   pkgV.bind("$$qn", "ti.platforms.evm6424.");
   pkgV.bind("$vers", Global.newArray("1, 0, 0, 0"));
   Value.Map atmap = (Value.Map) pkgV.getv("$attr");
   atmap.seal("length");
   imports.clear();
   imports.add(Global.newArray("ti.catalog.c6000", Global.newArray()));
   imports.add(Global.newArray("xdc.platform", Global.newArray(1, 0, 1)));
   pkgV.bind("$imports", imports);
   StringBuilder sb = new StringBuilder();
   sb.append("var pkg = xdc.om['ti.platforms.evm6424'];\n");
   sb.append("if (pkg.$vers.length >= 3) {\n");
   sb.append("pkg.$vers.push(Packages.xdc.services.global.Vers.getDate(xdc.csd() + '/..'));\n");
   sb.append("}\n");
   sb.append("pkg.build.libraries = [\n");
   sb.append("];\n");
   sb.append("pkg.build.libDesc = [\n");
   sb.append("];\n");
   sb.append("if('suffix' in xdc.om['xdc.IPackage$$LibDesc']) {\n");
   sb.append("}\n");
   Global.eval(sb.toString());
 }
  public void createBuildings() {
    bList = new ArrayList<Building>();

    // resource
    bList.add(new Building("Gold Mine", 3, 3, 960, 7));
    bList.add(new Building("Elixir Collector", 3, 3, 960, 7));
    // bList.add(new Building("Dark Elixir Drill", 3, 3, 1160, 3));
    bList.add(new Building("Gold Storage", 3, 3, 2100, 4));
    bList.add(new Building("Elixir Storage", 3, 3, 2100, 4));
    // bList.add(new Building("Dark Elixir Storage", 3, 3, 3200, 1));
    // bList.add(new Building("Builder Hut", 2, 2, 250, 5));

    // army
    bList.add(new Building("Army Camp", 5, 5, 500, 4));
    bList.add(new Building("Barracks", 3, 3, 860, 4));
    // bList.add(new Building("Dark Barracks", 3, 3, 900, 2));
    // bList.add(new Building("Laboratory", 4, 4, 950, 1));
    // bList.add(new Building("Spell Factory", 3, 3, 615, 1));
    // bList.add(new Building("Barbarian King Altar", 3, 3, 250, 1));
    // bList.add(new Building("Dark Spell Factory", 3, 3, 750, 1));
    // bList.add(new Building("Archer Queen Altar", 3, 3, 250, 1));

    // other
    bList.add(new Building("Town Hall", 4, 4, 5500, 1));
    bList.add(new Building("Clan Castle", 3, 3, 3400, 1));

    // defense
    bList.add(new Building("Archer Tower", 3, 3, 1050, 7));
    bList.add(new Building("Cannon", 3, 3, 1260, 6));
    bList.add(new Building("Wall", 1, 1, 7000, 275));
    // bList.add(new Building("Air Sweeper", 2, 2, 1000, 2));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
  }
Ejemplo n.º 30
0
  public static void main(String[] args) {
    ArrayList<Pattern> patterns = new ArrayList<Pattern>();
    ArrayList<Cut> cuts;
    ArrayList<Garment> garments;

    patterns.add(new Pattern(2, 2, 1, "Tie"));
    patterns.add(new Pattern(2, 6, 4, "Skirt"));
    patterns.add(new Pattern(4, 2, 3, "Blouse"));
    patterns.add(new Pattern(5, 3, 5, "Dress"));
    int width = 30;
    int height = 15;
    ClothCutter cutter = new ClothCutter(width, height, patterns);
    System.out.println("Optimized value: " + cutter.optimize());
    cuts = cutter.getCuts();
    garments = cutter.getGarments();

    ClothPanel panel = new ClothPanel(width, height);
    JFrame frame = new JFrame("A luxurious bolt of fabric");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    sleep(1000);
    for (int i = 0; i < cuts.size(); i++) {
      panel.drawCut(cuts.get(i));
      sleep(100);
    }
    for (int i = 0; i < garments.size(); i++) {
      System.out.println(garments.get(i));
      panel.drawGarment(garments.get(i));
      sleep(100);
    }
  }