私は、組み込みのJava APIやファンシー関数を使用せずにデカルト積とセットと関連したテキストブックから問題を解決しようとしています。Javaの2つのデカルト積のデカルト積
例えば セットAは、= {1,3,4}
セットBに含ま= {2,5}
それらの製品は、この結果に{(1,2)をもたらすであろう含有(1,5)、(3,2)、(3,5)、(4,2)、(4,5)}
各セットでさまざまな機能を実行するためのいくつかの方法を書いていますが、ここでは私が思いついたものこれをセットにどのように実装できますか?
public String cartesian(Set other)
{
String result = "";
int res;
for (int i = 0; i < this.size; ++i)
{
for (int j = 0; j < other.size; ++j)
{
//System.out.println("@@@@@"+ other.size);
//result = data[i] + ""+ other[i] + "";
//res = data[i] *= other.data[j];
}
}
return result;
}
このメソッドは結果を文字列として返します。私の論理は、同時に各セットの要素を取得することですが、私はそれらを一緒に交差する方法を考えて立ち往生しています。
ここに私のコードの残りの部分があります。
public class Sets {
public static void main(String[] args)
{
Set set1;
set1 = new Set();
Set set2 = new Set();
set1.add(1);
set1.add(2);
set1.add(3);
set2.add(3);
set2.add(4);
/*set2.add(4);
set2.add(5);*/
//System.out.println(set1.difference(set2));
System.out.println(set1.cartesianReformed(set2));
}
}
ユーザー定義Set
クラスは、このような
class Set
{
private int[] data;
private int size;
public Set()
{
data = new int[20];
size = 0;
}
public void add(int value)
{
int[] copy;
//avoiding duplicates
if (!in(value))
{
if (size > data.length)
{
copy = new int[data.length * 2];
System.arraycopy(data, 0, copy,0,data.length);
data = copy;
}
data[size] = value;
size++;
}
else
{
System.out.println("You are trying to insert a number that's already here ---> " + value);
}
}
public String toString()
{
String result = "{";
for(int i = 0; i < size; i++)
{
result += "" + data[i];
//Add a comma after all but the last item
if (i < size - 1)
{
result += ",";
}
}
result += "}";
return result;
}
public boolean in(int value)
{
boolean result = false;
for(int i = 0; i < size; i++)
{
if (data[i] == value)
{
result = true;
}
}
return result;
}
public Set intersection(Set other)
{
Set result = new Set();
for (int i = 0; i < size; ++i)
{
if (other.in(data[i]))
{
result.add(data[i]);
}
}
return result;
}
public boolean equals(Set other)
{
boolean result = false;
int count = 0;
for (int i = 0; i < size; ++i) //iterating over this
{
if (other.in(data[i]))
{
count++;
}
if (count == size)
{
result = true;
}
}
return result;
}
public Set difference(Set other)
{
Set result = new Set();
for(int i = 0; i < size; ++i)
{
if (!other.in(data[i]))
{
result.add(data[i]);
}
}
return result;
}
public String cartesian(Set other)
{
String result = "";
int res;
for (int i = 0; i < this.size; ++i)
{
for (int j = 0; j < other.size; ++j)
{
//System.out.println("@@@@@"+ other.size);
//result = data[i] + ""+ other[i] + "";
//res = data[i] *= other.data[j];
}
}
return result;
}
public Set union(Set other) {
Set result = (Set)other.clone();
for (int i = 0; i < size; i++) {
result.add(data[i]);
}
return result;
}
public Object clone() {
Set result = new Set();
for (int i = 0; i < size; i++) {
result.add(data[i]);
}
return result;
}
}
このような文字列の出力を生成するか、 – v010dya
2つのセットのデカルト積を得て、出力を生成することです@ v010dya – ekeith