Skip to content

Instantly share code, notes, and snippets.

@jeffque
Last active May 24, 2023 11:06
Show Gist options
  • Save jeffque/c8af434d20b16c986eea5e497ea99750 to your computer and use it in GitHub Desktop.
Save jeffque/c8af434d20b16c986eea5e497ea99750 to your computer and use it in GitHub Desktop.
Dado um array de elementos, descubra o menor deles.
import java.util.Arrays;
import java.util.stream.Collector;
class SegundoMenor {
static class AB {
int a, b;
boolean primeiro;
boolean segundo;
void accept(int x) {
if (!primeiro) {
primeiro = true;
a = x;
return;
}
if (!segundo) {
segundo = true;
if (x < a) {
b = a;
a = x;
} else {
b = x;
}
return;
}
if (x < a) {
b = a;
a = x;
} else if (x < b) {
b = x;
}
}
int b() {
return b;
}
AB combine(AB other) {
int a1, b1, a2, b2;
final int af, bf;
a1 = this.a;
b1 = this.b;
a2 = other.a;
b2 = other.b;
if (a1 <= a2) {
af = a1;
if (a2 <= b1) {
bf = a2;
} else {
bf = b1;
}
} else {
af = a2;
if (a1 <= b2) {
bf = a1;
} else {
bf = b2;
}
}
AB n = new AB();
n.a = af;
n.b = bf;
return n;
}
}
public static void main(String[] args) {
int[] x = {10, 5, 3, 8, 7};
final var segundoMenor = Collector.of(AB::new, AB::accept, AB::combine, AB::b);
System.out.println(Arrays.stream(x).boxed().collect(segundoMenor));
}
}
class SegundoMenorSimpler {
public static void main(String[] args) {
int[] x = {10, 5, 3, 8, 7};
if (x.length >= 2) {
int a, b;
a = x[0];
b = x[1];
if (b < a) {
int tmp = b;
b = a;
a = tmp;
}
for (int i = 2; i < x.length; i++) {
int c = x[i];
if (c < a) {
b = a;
a = c;
} else if (c < b) {
b = c;
}
}
System.out.println(b);
} else {
System.out.println("não tem elementos o suficiente");
}
}
}
class SegundoMenorSimpler2 {
static class AB {
int a, b;
boolean primeiro;
boolean segundo;
void accept(int x) {
if (!primeiro) {
primeiro = true;
a = x;
return;
}
if (!segundo) {
segundo = true;
if (x < a) {
b = a;
a = x;
} else {
b = x;
}
return;
}
if (x < a) {
b = a;
a = x;
} else if (x < b) {
b = x;
}
}
int b() {
return b;
}
}
public static void main(String[] args) {
int[] x = {10, 5, 3, 8, 7};
AB ab = new AB();
for (int n: x) {
ab.accept(n);
}
System.out.println(ab.b());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment