Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:com.liferay.portal.service.impl.UserLocalServiceImpl.java

protected void updateUserGroupRoles(User user, long[] groupIds, long[] organizationIds,
        List<UserGroupRole> userGroupRoles) throws PortalException, SystemException {

    if (userGroupRoles == null) {
        return;/*from ww w.  j a va 2 s.  c o  m*/
    }

    List<UserGroupRole> previousUserGroupRoles = userGroupRolePersistence.findByUserId(user.getUserId());

    for (UserGroupRole userGroupRole : previousUserGroupRoles) {
        if (userGroupRoles.contains(userGroupRole)) {
            userGroupRoles.remove(userGroupRole);
        } else {
            userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
        }
    }

    long[] validGroupIds = null;

    if (groupIds != null) {
        validGroupIds = ArrayUtil.clone(groupIds);
    } else {
        validGroupIds = user.getGroupIds();
    }

    if (organizationIds == null) {
        organizationIds = user.getOrganizationIds();
    }

    long[] organizationGroupIds = new long[organizationIds.length];

    for (int i = 0; i < organizationIds.length; i++) {
        long organizationId = organizationIds[i];

        Organization organization = organizationPersistence.findByPrimaryKey(organizationId);

        Group organizationGroup = organization.getGroup();

        organizationGroupIds[i] = organizationGroup.getGroupId();
    }

    validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);

    Arrays.sort(validGroupIds);

    for (UserGroupRole userGroupRole : userGroupRoles) {
        if (Arrays.binarySearch(validGroupIds, userGroupRole.getGroupId()) >= 0) {

            userGroupRoleLocalService.addUserGroupRole(userGroupRole);
        }
    }
}

From source file:com.cohort.util.String2.java

/**
 * Find the first element which is &gt;= s in an ascending sorted array.
 *
 * @param sar an ascending sorted String[] which currently may not have duplicate values
 * @param s//from  w ww.j  a  va2s . c om
 * @return the index of the first element which is &gt;= s in an ascending sorted array.
 *   If s &lt; the smallest element, this returns 0.
 *   If s is null or s &gt; the largest element, this returns sar.length (no element is appropriate).
 */
public static int binaryFindFirstGE(String[] sar, String s) {
    if (s == null)
        return sar.length;
    int i = Arrays.binarySearch(sar, s);

    //an exact match; look for duplicates
    if (i >= 0) {
        while (i > 0 && sar[i - 1].compareTo(s) >= 0)
            i--;
        return i;
    }

    return -i - 1; //the insertion point,  0.. sar.length
}

From source file:com.cohort.util.String2.java

/**
 * Find the closest element to s in an ascending sorted array.
 *
 * @param sar an ascending sorted String[].
 *   It the array has duplicates and s equals one of them,
 *   it isn't specified which duplicate's index will be returned.
 * @param s//from  ww w  . j  a  va  2s  .com
 * @return the index of the element closest to s.
 *   If s is null, this returns -1.
 */
public static int binaryFindClosest(String[] sar, String s) {
    if (s == null)
        return -1;
    int i = Arrays.binarySearch(sar, s);
    if (i >= 0)
        return i; //success

    //insertionPoint at end point?
    int insertionPoint = -i - 1; //0.. sar.length
    if (insertionPoint == 0)
        return 0;
    if (insertionPoint >= sar.length)
        return sar.length - 1;

    //insertionPoint between 2 points 
    //do they differ at a different position?
    //make all the same length
    int preIndex = insertionPoint - 1;
    int postIndex = insertionPoint;
    String pre = sar[preIndex];
    String post = sar[postIndex];
    int longest = Math.max(s.length(), Math.max(pre.length(), post.length()));
    String ts = s + makeString(' ', longest - s.length());
    pre += makeString(' ', longest - pre.length());
    post += makeString(' ', longest - post.length());
    for (i = 0; i < longest; i++) {
        char ch = ts.charAt(i);
        char preCh = pre.charAt(i);
        char postCh = post.charAt(i);
        if (preCh == ch && postCh != ch)
            return preIndex;
        if (preCh != ch && postCh == ch)
            return postIndex;
        if (preCh != ch && postCh != ch) {
            //which one is closer
            return Math.abs(preCh - ch) < Math.abs(postCh - ch) ? preIndex : postIndex;
        }
    }
    //shouldn't all be equal
    return preIndex;
}

From source file:com.ah.ui.actions.hiveap.HiveApUpdateAction.java

/**
 *
 * @param initIds -/*w ww. j a  v a2s.com*/
 * @param supportPlatforms -
 * @param supportVer -
 */
private void generateFilteredMessage(Set<Long> initIds, short[] supportPlatforms, String supportVer) {
    boolean hasUnsupportVer = false;
    boolean hasUnsupportPlat = false;
    String query = "select softVer, hiveApModel from " + HiveAp.class.getCanonicalName();
    List<?> list = QueryUtil.executeQuery(query, null, new FilterParams("id", initIds));
    Arrays.sort(supportPlatforms);
    for (Object object : list) {
        Object[] objects = (Object[]) object;
        String deviceVer = (String) objects[0];
        Short platform = (Short) objects[1];
        if (NmsUtil.compareSoftwareVersion(deviceVer, supportVer) < 0) {
            hasUnsupportVer = true;
            break;
        }
        if (null != platform) {
            int pos = Arrays.binarySearch(supportPlatforms, platform.shortValue());
            if (pos < 0) {
                hasUnsupportPlat = true;
                break;
            }
        }
    }
    if (hasUnsupportVer) {
        unsupportedApsMessage = MgrUtil.getUserMessage("error.hiveAp.feature.discard.unsupport.version",
                supportVer);
    }
    if (hasUnsupportPlat) {
        addActionPermanentErrorMsg(MgrUtil.getUserMessage("error.hiveAp.feature.discard.unsupport.model",
                LSevenSignatures.getAllSupportedPlatformsString()));
    }
}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Determine if a GTS' values are normally distributed.
 * Works for numerical GTS only//from   www .  j a  v  a 2s  .co m
        
 * @param gts GTS to check
 * @param buckets Number of buckets to distribute the values in
 * @param pcterror Maximum acceptable percentage of deviation from the mean of the bucket sizes
 * @param bessel Should we apply Bessel's correction when computing sigma
 * 
 * @return true if the GTS is normally distributed (no bucket over pcterror from the mean bucket size)
 */
public static boolean isNormal(GeoTimeSerie gts, int buckets, double pcterror, boolean bessel) {
    //
    // Return true if GTS has no values
    //

    if (0 == gts.values) {
        return true;
    }

    //
    // Return false if GTS is not of type LONG or DOUBLE
    //

    if (TYPE.DOUBLE != gts.type && TYPE.LONG != gts.type) {
        return false;
    }

    double[] musigma = musigma(gts, bessel);
    double mu = musigma[0];
    double sigma = musigma[1];

    //
    // Constant GTS are not gaussian
    //

    if (0.0D == sigma) {
        return false;
    }

    //
    // Retrieve bounds
    //

    double[] bounds = SAXUtils.getBounds(buckets);

    int[] counts = new int[bounds.length + 1];

    //
    // Loop over the values, counting the number of occurrences in each interval
    //

    for (int i = 0; i < gts.values; i++) {
        double v = ((double) GTSHelper.valueAtIndex(gts, i) - mu) / sigma;

        int insertion = Arrays.binarySearch(bounds, v);

        //(-(insertion_point) - 1);

        if (insertion >= 0) {
            counts[insertion]++;
        } else {
            counts[-(1 + insertion)]++;
        }
    }

    //
    // Compute the mean bucket size
    //

    double mean = gts.values / counts.length;

    //
    // Check that each bucket is with 'pcterror' of the mean
    //

    for (int i = 0; i < counts.length; i++) {
        if (Math.abs(1.0D - (counts[i] / mean)) > pcterror) {
            return false;
        }
    }

    return true;
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static GeoTimeSerie quantize(GeoTimeSerie gts, double[] bounds, Object[] values)
        throws WarpScriptException {

    // FIXME(hbs): we could support String types too
    if (TYPE.DOUBLE != gts.type && TYPE.LONG != gts.type) {
        throw new WarpScriptException("Can only quantify numeric Geo Time Series.");
    }/*from   w ww  . j  a v a 2s. c om*/

    GeoTimeSerie quantified = gts.cloneEmpty();

    //
    // Loop over the values, counting the number of occurrences in each interval
    //

    for (int i = 0; i < gts.values; i++) {
        double v = ((Number) GTSHelper.valueAtIndex(gts, i)).doubleValue();

        int insertion = Arrays.binarySearch(bounds, v);

        //(-(insertion_point) - 1);

        if (null == values) {
            if (insertion >= 0) {
                GTSHelper.setValue(quantified, GTSHelper.tickAtIndex(gts, i), GTSHelper.locationAtIndex(gts, i),
                        GTSHelper.elevationAtIndex(gts, i), insertion, false);
            } else {
                GTSHelper.setValue(quantified, GTSHelper.tickAtIndex(gts, i), GTSHelper.locationAtIndex(gts, i),
                        GTSHelper.elevationAtIndex(gts, i), -(1 + insertion), false);
            }
        } else {
            if (insertion >= 0) {
                GTSHelper.setValue(quantified, GTSHelper.tickAtIndex(gts, i), GTSHelper.locationAtIndex(gts, i),
                        GTSHelper.elevationAtIndex(gts, i), values[insertion], false);
            } else {
                GTSHelper.setValue(quantified, GTSHelper.tickAtIndex(gts, i), GTSHelper.locationAtIndex(gts, i),
                        GTSHelper.elevationAtIndex(gts, i), values[-(1 + insertion)], false);
            }
        }
    }

    return quantified;
}