2016-11-16 4 views
1

私はので、私は何を理解することができますブルートフォースを使用して、この質問に答えるためにしようとしているを使用して答えるInterviewCakeなぜ私のロジックが機能していないのか理解していない。ここで私はこれまで試したものです:製品の-他-番号は力ずく

public class EveryInteger { 

    public static void main(String[] args) { 

     int a1[] = {1, 7, 3, 4}; 
     int a2[] = new int[4]; 
      for(int i =0; i<a1.length; i++){ 
      int index = a1[i]; 
      int sum = 0; 

      for(int j =0; j<a1.length; j++){ 
       if(a1[i]==a1[j]){ 
        continue; 
       } 

       sum = index * a1[j]; 
       a2[i] = sum; 
       System.out.println(a2[i]); 
      } 
      } 
    } 

は、誰もがあなたがループのための2つを使用してこの問題を解決する方法を見せていただけますか?

答えて

0

suma2に割り当てて、これを内側ループに印刷しますが、これは間違っています。代わりに、外側のループでそれをやってみてください。

public class EveryInteger { 

    public static void main(String[] args) { 
     int a1[] = {1, 7, 3, 4}; 
     int a2[] = new int[4]; 
      for(int i =0; i<a1.length; i++){ 
      int sum = 1; 

      for(int j =0; j<a1.length; j++){ 
       if(a1[i]==a1[j]){ 
        continue; 
       } 
       sum *= a1[j]; 
      } 
      a2[i] = sum; 
      System.out.println(a2[i]); 
      } 
    } 
} 
3

問題のカップルがここにあります。必要に応じて結果が

int[] input = {1,7,3,4}; 
int[] output = new int[input.length]; 

for(int i = 0; i < input.length; i++) { 
    // Accumulates the multiplications. 
    int acc = 1; 
    for(int j = 0; j < input.length; j++) { 
    // check, if not at the same index. 
    if(j != i) { 
     // only then multiply the current number with the accumulator. 
     acc *= input[j]; 
    } 
    } 
    // finally write the accumulated product to the output array. 
    output[i] = acc; 
} 

System.out.println(Arrays.toString(output)); 

// defining an array like this is confusing because the type is not immediately clear, rather use int[] a1 = ... 
int a1[] = {1, 7, 3, 4}; 
// a2 should always have the same length as a1, so use a1.length 
int a2[] = new int[4]; 
for(int i =0; i<a1.length; i++){ 
    // index is a little confusing, since it's not the index but the value at i 
    int index = a1[i]; 
    // sum is also confusing, since you're working with multiplication here 
    // Additionally with multiplication involved, initialize that to 1 
    int sum = 0; 

    for(int j =0; j<a1.length; j++){ 
     // comparing only j and i would be sufficient here without accessing the array twice 
     if(a1[i]==a1[j]){ 
      continue; 
     } 

     // Instead of accumulating the product you reassign it every time, effectively deleting the previous value. 
     sum = index * a1[j]; 
     a2[i] = sum; 
     System.out.println(a2[i]); 
    } 
} 

ソリューションは、次のようになります。 :

[84, 12, 28, 21]