私はJavaで私の知識をリフレッシュしてcodewarsから運動に取り組んでいます。要素が「同じ」であれば、問題は、2つの配列を比較することです。「同じ」の意味は、「B」の要素が「」順序に関係なく、乗の要素であるということです。私がやろうとしたことが解決策には「B」内の要素の平方根を取得しない、それは「」Math.sqrt()を使用して要素に存在するかどうかをチェックすることです。以下のためのパラメータが含まれていると私は)(それを使用する場合しかし、それは常にfalseを返します。
要素「B」は本当にないの平方根は、特定の要素をチェックする場合は、他の「」、私はシンプルにしようとした中に存在するのであれば確認してください。しかし、私はどこに問題が上昇だMath.sqrt()、とそれを組み込むとき。
ここで設定し、AとBの要素があります
int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};
私は、リストに変換されていること
List<Integer> setAList = Arrays.stream(setA)//int[] setA - parameter of a function
.boxed()
.collect(Collectors.toList());
List<Integer> setBList = Arrays.stream(setB)//int[] setB - parameter of a function
.boxed()
.collect(Collectors.toList());
私は含まれています()メソッドを利用するために配列をリストに変換します。私は、特定の要素をチェックしようとしたとき、これは私のコードです
double sqrd = Math.sqrt(setBList.get(6));
return setAList.get(5) == sqrd ? true : false;
真 - そしてそれは期待される結果を与えました。今ここに、私はループのためにそれを組み込んだときのコードです
boolean same = true;
for(int indexB : setB) {
same = setAList.contains(Math.sqrt(indexB)) ? true : false;
System.out.println(Math.sqrt(indexB) + " " + same);
}
そして、ここでの結果です
11.0 false
121.0 false
144.0 false
19.0 false
161.0 false
19.0 false
144.0 false
19.0 false
false
最初に私には問題は、データ型であるかもしれないが、私はintに、二重のキャスト試してみましたが、私はまだ同じ結果を取得しています。けれども
ない直接的な答えはなく、問題のこの種を回避するための回避策:
他の回答で説明したように、あなたがに対処する必要があるため、あなたの問題は、キャストの問題であるdouble
とint
の値と顔キャスティングの問題にはありません。
それを回避する方法は、正方形のAの値の代わりに、あなただけの今までに対処Bの値の平方根を計算する。この方法にあるint
値
int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};
// Make a list containing the squares out of the b array
List<Integer> squares = Arrays.stream(b)
.boxed()
.collect(Collectors.toList());
// square all the values in B,
// and check that all the resultant values are present in the squares list
boolean same = Arrays.stream(a) // Stream<Integer> containing values in array a
.map(i -> i* i) // Stream<Integer> containing values in array a squared
.allMatch(squares::contains); // reduce to a boolean insuring that all values in the Stream<Integer> are present in the squares list
System.out.println(same);