微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

确定两个元素是否在二维数组中的同一行或同一列中的最快方法是什么?

如何解决确定两个元素是否在二维数组中的同一行或同一列中的最快方法是什么?

作为我的一个程序的一部分,我试图检查二维数组中的两个元素是否属于同一行或列。我知道可能有很多方法可以解决这个问题,主要是使用循环和遍历数组,但我只是想知道:有没有什么快速方法来确定这一点?

假设我有一个看起来像 {{1,2},{3,4},{5,6}} 的二维数组。是否有任何快速方法可以确定 12 属于同一行?几乎可以在 if 语句中将其计算为 “如果 item x 与 item y 属于同一行,那么这样做等等”?如果没有,那么最快的方法是什么?

解决方法

这是一种处理行的方法。

int[][] v = {{1,2},{3,4},{5,6}};
System.out.println(rowContains(v,2,3));
System.out.println(rowContains(v,5,6));

印刷品

false
true

方法

  • 流式处理单个 d 数组并忽略重复项
  • 在查找值时计数过滤器。
  • 如果任何最终计数为 2,则返回 true。
public static boolean rowContains(int[][] v,int v1,int v2) {
    return Arrays.stream(v)
            .map(arrs -> Arrays.stream(arrs)
                    .distinct().filter(a -> a == v1 || a == v2)
                    .count()).anyMatch(a -> a == 2);
}

对于列,最简单的方法是编写一个方法来转置列和行并重新运行该方法。

,

使用比使用更容易解决这个任务。您可以使用 binarySearch 方法。

此解决方案也适用于参差不齐的二维数组和无限数量的要搜索的元素。

public static void main(String[] args) {
    int[][] arr = {{1,3},{4,5},{6,7,8}};
    System.out.println(sameRow(arr,4,5)); // true
    System.out.println(sameCol(arr,3,8)); // true
}
/**
 * @param arr      2d array.
 * @param elements 1d array of elements to search for.
 * @return whether any column of a 2d array contains all elements from a 1d array.
 */
public static boolean sameCol(int[][] arr,int... elements) {
    return IntStream
            // iterate through the columns
            .iterate(0,i -> i + 1)
            // take an array of values from the column,if any
            .mapToObj(i -> Arrays
                    // iterate through the rows
                    .stream(arr)
                    // take those rows where this column is present
                    .filter(row -> row.length > i)
                    // take the value from the column
                    .mapToInt(row -> row[i])
                    // int[] - column
                    .toArray())
            // until the columns are still present
            .takeWhile(col -> col.length > 0)
            // whether any column contains all the search elements
            .anyMatch(col -> containsAll(col,elements));
}
/**
 * @param arr      2d array.
 * @param elements 1d array of elements to search for.
 * @return whether any row of a 2d array contains all elements from a 1d array.
 */
public static boolean sameRow(int[][] arr,int... elements) {
    return Arrays.stream(arr).anyMatch(row -> containsAll(row,elements));
}
/**
 * @param a first array.
 * @param b second array.
 * @return whether the first array contains all elements from the second array.
 */
public static boolean containsAll(int[] a,int[] b) {
    return Arrays.stream(b).allMatch(i -> Arrays.binarySearch(a,i) > -1);
}

另见:
Filling a jagged 2d array first by columns
Check if one array is a subset of the other array - special case

,

此代码在没有Java 7中工作。使用 binarySearch 方法的方法相同。接受不规则的二维数组和无限数量的要搜索的元素。

还有循环,这个任务用比用更容易解决。

 function main() {
      // Retrieve values from API.
      var apikey = '*********'; // Please input your key.
      var apisecret = '**********'; // Please input your secret.
      var nonce = Number(new Date().getTime() / 1000).toFixed(0);
      var uri = 'https://bittrex.com/api/v1.1/account/getbalances?apikey=' + apikey + '&nonce=' + nonce;
      var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,uri,apisecret);
      sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
      var params = {
        method: "get",headers: {Apisign: sign}

  }
  var response = UrlFetchApp.fetch(uri,params);
  var getContext= response.getContentText();
  var parsedata = JSON.parse(getContext);
  
  console.log(getContext)  // Here,the response value can be confirmed at the log.

  // Use Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var balancesSheet = ss.getSheetByName("BITTREX 2");
  var balancesRange = balancesSheet.getRange("A1:X");
  var balancesListValues = balancesRange.getValues();
  balancesSheet.getRange(1,1,balancesRange.getHeight(),balancesRange.getWidth()).setValues(balancesListValues);

  var values = parsedata.result.map(({Currency,Available}) => [Currency,Available]);
  balancesSheet.getRange(1,values.length,values[0].length).setValues(values);
}
public static void main(String[] args) {
    int[][] arr = {{1,5));    // true
    System.out.println(sameCol(arr,8));    // true
    System.out.println(sameCol(arr,7)); // true
}
/**
 * @param arr      2d array.
 * @param elements 1d array of elements to search for.
 * @return whether any column of a 2d array contains all elements from a 1d array.
 */
public static boolean sameCol(int[][] arr,int... elements) {
    // iterate through the columns
    for (int i = 0; ; i++) {
        // take an array of values from the column,if any
        int[] col = new int[arr.length];
        // column counter
        int j = 0;
        // iterate through the rows
        for (int[] row : arr)
            // take those rows where this column is present
            if (row.length > i)
                // take the value from the column
                // and increase the counter
                col[j++] = row[i];
        // until the columns are still present
        if (j == 0) break;
        // if this column contains all the search elements
        if (containsAll(Arrays.copyOf(col,j),elements))
            return true;
    }
    return false;
}
/**
 * @param arr      2d array.
 * @param elements 1d array of elements to search for.
 * @return whether any row of a 2d array contains all elements from a 1d array.
 */
public static boolean sameRow(int[][] arr,int... elements) {
    for (int[] row : arr)
        if (containsAll(row,elements))
            return true;
    return false;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。