Skip to content

Commit 2017ed3

Browse files
committed
Re-write polynomial mult to eliminate indices.
1 parent 1e43cd4 commit 2017ed3

File tree

1 file changed

+49
-38
lines changed

1 file changed

+49
-38
lines changed

src/solvers/enumpoly/poly.imp

Lines changed: 49 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -89,54 +89,65 @@ List<Monomial<T>> Polynomial<T>::Mult(const List<Monomial<T>> &One,
8989
return answer;
9090
}
9191

92-
for (size_t i = 1; i <= One.size(); i++) {
93-
for (size_t j = 1; j <= Two.size(); j++) {
94-
const Monomial<T> next = One[i] * Two[j];
92+
for (const auto &m1 : One) {
93+
for (const auto &m2 : Two) {
94+
Monomial<T> next = m1 * m2;
95+
auto nextExp = next.ExpV();
9596

9697
if (answer.empty()) {
9798
answer.push_back(next);
99+
continue;
98100
}
99101

100-
else {
101-
int bot = 1;
102-
int top = answer.size();
103-
if (answer[top].ExpV() < next.ExpV()) {
104-
answer.push_back(next);
105-
}
106-
else if (answer[bot].ExpV() > next.ExpV()) {
107-
answer.push_front(next);
102+
auto it_first = answer.begin();
103+
auto it_last = std::prev(answer.end());
104+
105+
if (it_last->ExpV() < nextExp) {
106+
answer.push_back(next);
107+
continue;
108+
}
109+
if (it_first->ExpV() > nextExp) {
110+
answer.push_front(next);
111+
continue;
112+
}
113+
if (it_first->ExpV() == nextExp) {
114+
*it_first += next;
115+
continue;
116+
}
117+
if (it_last->ExpV() == nextExp) {
118+
*it_last += next;
119+
continue;
120+
}
121+
// Search for correct place to insert or combine
122+
bool handled = false;
123+
124+
auto prev = answer.begin();
125+
auto it = std::next(prev);
126+
127+
for (; it != answer.end(); ++it, ++prev) {
128+
auto e_prev = prev->ExpV();
129+
auto e = it->ExpV();
130+
131+
if (e == nextExp) {
132+
*it += next;
133+
handled = true;
134+
break;
108135
}
109-
else {
110-
if (answer[bot].ExpV() == next.ExpV()) {
111-
top = bot;
112-
}
113-
else if (answer[top].ExpV() == next.ExpV()) {
114-
bot = top;
115-
}
116-
117-
while (bot < top - 1) {
118-
const int test = bot + (top - bot) / 2;
119-
if (answer[test].ExpV() == next.ExpV()) {
120-
bot = top = test;
121-
}
122-
else if (answer[test].ExpV() < next.ExpV()) {
123-
bot = test;
124-
}
125-
else { // (answer[test].ExpV() > next.ExpV())
126-
top = test;
127-
}
128-
}
129-
130-
if (bot == top) {
131-
answer[bot] += next;
132-
}
133-
else {
134-
answer.insert(std::next(answer.begin(), top - 1), next);
135-
}
136+
137+
if (e_prev < nextExp && nextExp < e) {
138+
answer.insert(it, next);
139+
handled = true;
140+
break;
136141
}
137142
}
143+
144+
// If no place found, append
145+
if (!handled) {
146+
answer.push_back(next);
147+
}
138148
}
139149
}
150+
140151
return answer;
141152
}
142153

0 commit comments

Comments
 (0)