簡體   English   中英

乘法和移位數組元素

[英]Multiply and shift array elements

我已經使用這種算法已有一段時間了,但我還是無法理解。 這是需要發生的事情:

我有一個數組1(行不移動) .10 .15 .20 .30

和數組2(將向左移動) .25 .30 .28 .11

我需要的算法如下。

.10 .15 .20 .30
.25 .30 .28 .11

multiply .10 * .25
multiply .15 * .30
multiply .20 * .28
multiply .30 * .11

然后:

  • 將這些乘法的總和
  • 將底部數組索引1向左移動,並將索引1中的元素固定到數組的背面,因此現在乘法將是

     .10 .15 .20 .30 .30 .28 .11 .25 
  • 重復乘法

  • 重復這些乘法的總和

這將一直持續到我們循環一次。

我的嘗試:

float[] statProp = {.25 .30 .28 .11};
float[] statProperties = {.10 .15 .20 .30}
float statPropTotal=0;
for(int z=0; z<5; z++){
    for(int x =0; x < 5)
    statProp[z] = stat[z+1] * (float)statProperties[z];
}
for(int z=0; z<5; z++){
     float statPropTotal=0;
     statPropTotal += (float)statProp[x];
}

據我所知(一些性能修復):

public static void main(String[] args) {
    double[] arr1 = {.10, .15, .20, .30};
    double[] arr2 = {.25, .30, .28, .11};

    double sum = 0;
    int count = 0;
    while (count < arr1.length) {
        int j = count;
        for (int i = 0; i < arr1.length; i++, j++) {
            if (j > arr1.length - 1) {
                j = 0;
            }
            sum += arr1[i] * arr2[j];
        }
        count++;
    }
    System.out.println(sum);
}

這是一些偽代碼,以向您提示正在使用的算法(讓我們擁有float[] a1float[] a2 ):

在獲取代碼之前,讓我們想象一下,我們只是在使數組彼此相對滑動,而不是更改a2值的索引:

.10 .15 .20 .30
        .25 .30 .28 .11
__2__↑   ↑-1-↑   ↑__2__

因此,我們可以針對第1部分和第2部分使用兩個循環來計算乘法/總和

double sum = 0;

//main loop, where i represents by how much you are shifting a2
for(int i = 0 ; i < a2.length ; i++) {

    //loop for part #1
    for(int j = i ; j < a2.length ; j++) {
        sum = sum + (a1[?] * a2[j]);
    }

    //loop for part #2
    for(int j = 0 ; j < i ; j++) {
        sum = sum + (a1[j] * a2[?]);
    }
}

在這里,我留下了一些邏輯供您理解,但是一切都在那里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM