Mars Lander - Episode 2 – CodinGame solution in Java
Find the flat landing segment, then each turn pick a behaviour based on the lander's situation: if it is not above the zone, brake when it moves too fast or the wrong way and otherwise tilt about 21° toward the zone at full power to accelerate without losing altitude; once above the zone, kill the horizontal speed by pointing the thrust against the velocity vector, and straighten to 0° for the final descent. The angle that cancels a velocity is asin(hSpeed / speed) in degrees.
The problem
The terrain is a polyline of up to 30 points on a 7000 × 3000 m map, containing exactly one flat segment at least 1000 m wide. The lander starts away from that zone, often with an initial horizontal speed, under Mars gravity of 3.711 m/s².
Each turn you output a rotation (−90 to 90 degrees) and a thrust power (0 to 4). The game limits changes to 15° and one power level per turn. To land you must touch the flat zone with angle 0, vertical speed at most 40 m/s and horizontal speed at most 20 m/s, without running out of fuel.
Approach, step by step
- Locate the flat zoneWhile reading the surface, compare each point's height with the previous one; two consecutive points at the same y define the landing segment's left x, right x and altitude.
- Get above the zoneIf the lander is outside the segment and moving away from it, or faster than about 80 m/s horizontally, brake. If it is moving toward the zone too slowly, tilt toward it at power 4. In between, fly level with power 3 or 4 to hold altitude.
- Brake by thrusting against the velocityAngle = asin(hSpeed / |v|) in degrees points the thrust opposite the motion: positive angles push toward negative x, so a ship moving right gets a positive angle. Combined with power 4 this removes speed as fast as possible.
- Hover while moving sidewaysTilting by θ at power 4 gives a vertical thrust of 4·cos θ. Choosing θ = acos(3.711 / 4) ≈ 21.9° exactly balances gravity, so the lander travels sideways at constant altitude instead of sinking.
- Final approachOnce above the zone with safe speeds, use angle 0 and enough power to keep the vertical speed under 40 m/s. Just above the ground, force angle 0 so that the 15° per turn limit does not leave you tilted on contact.
Complexity
O(N) setup, O(1) per turnO(1)Only the landing segment is kept from the surface. Each turn is a handful of comparisons and one trigonometric call.
Solution code
Mars Lander - Episode 2 – Java
Wraps the lander in a MarsLander class with small predicate methods (isOverTarget, goesInWrongDirection, goesTooFastHorizontally...) so the main loop reads like the decision tree. Safety margins of 5 m/s on speeds and 20 m on altitude absorb the lag caused by the rotation and power change limits.
import java.math.*;
import java.util.*;
class MarsLander {
private static final int Y_MARGIN = 20;
private static final int SPEED_MARGIN = 5;
private static final int MAX_DY = 40;
private static final int MAX_DX = 20;
private static final double GRAVITY = 3.711;
private int x, y, dx, dy, fuel, angle, power;
private int targetL, targetR, targetY;
public MarsLander() {}
public void init (int x, int y, int dx, int dy, int fuel, int angle, int power) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.fuel = fuel;
this.angle = angle;
this.power = power;
}
public void setTarget(int targetL, int targetR, int targetY) {
this.targetL = targetL;
this.targetR = targetR;
this.targetY = targetY;
}
public boolean isOverTarget() {
return targetL <= x && x <= targetR;
}
public boolean isFinishing() {
return y < targetY + Y_MARGIN;
}
public boolean hasSafeSpeed() {
return Math.abs(dx) <= MAX_DX - SPEED_MARGIN &&
Math.abs(dy) <= MAX_DY - SPEED_MARGIN;
}
public boolean goesInWrongDirection() {
return (x < targetL && dx < 0) || (targetR < x && dx > 0);
}
public boolean goesTooFastHorizontally() {
return Math.abs(dx) > 4*MAX_DX;
}
public boolean goesTooSlowHorizontally() {
return Math.abs(dx) < 2*MAX_DX;
}
/**
* returns the best angle to slow down marse lander
* (the angle directing thrust in the opposition direction to the mvmt)
*/
public int angleToSlow() {
double speed = Math.sqrt(dx*dx + dy*dy);
return (int) Math.toDegrees(Math.asin((double)dx / speed));
}
/**
* returns the exact angle to compensate gravity while
* going toward target
*/
public int angleToAimTarget() {
int angle = (int) Math.toDegrees(Math.acos(GRAVITY / 4.0));
if (x < targetL)
return -angle;
else if (targetR < x)
return angle;
else
return 0;
}
/**
* returns the thrust power needed to aim a null vertical speed
*/
public int powerToHover() {
return (dy >= 0) ? 3 : 4;
}
}
class Player {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
MarsLander ship = new MarsLander();
int N = in.nextInt();
// Looking for the landing area
int landX, landY, prevX, prevY;
prevX = prevY = -1;
for (int i = 0; i < N; i++) {
landX = in.nextInt();
landY = in.nextInt();
if (landY == prevY) {
ship.setTarget(prevX, landX, landY);
} else {
prevX = landX;
prevY = landY;
}
}
for (;;) {
/* The flight follows 2 steps :
- first the rover goes over the landing zone by
-- slowing if it goes faster than 4*MAX_HS, or in the wrong direction
-- accelerating while hovering until it reaches 2*MAX_HS if it goes in the right direction
-- waiting hovering if it has a speed between 2*MAX_HS and 4*MAX_HS
- then it slows down to meet speed specification (going back
to step 1 if it goes out of the landing zone)
*/
ship.init(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt());
if (!ship.isOverTarget()) {
if (ship.goesInWrongDirection() || ship.goesTooFastHorizontally())
System.out.println(ship.angleToSlow() + " 4");
else if (ship.goesTooSlowHorizontally())
System.out.println(ship.angleToAimTarget() + " 4");
else
System.out.println("0 " + ship.powerToHover());
}
else {
if (ship.isFinishing())
System.out.println("0 3");
else if (ship.hasSafeSpeed())
System.out.println("0 2");
else
System.out.println(ship.angleToSlow() + " 4");
}
}
}
}
Common mistakes
- Getting the angle sign backwardsIn Mars Lander a positive rotation tilts the ship to the left, so the thrust pushes toward negative x. If your lander accelerates when it should brake, flip the sign.
- Ignoring the per-turn limitsYou may request any value, but the game only moves 15° and one power level per turn. A ship asked to go from 60° to 0° at the last moment still lands tilted, so plan the straightening a few turns before touchdown.
- Tilting at power 3 while travelling4·cos θ must stay above 3.711 to avoid sinking. At power 3 any tilt makes the lander lose altitude, which crashes it on the high-ground tests.
- Only checking horizontal positionSome tests have mountains between start and zone. If you descend before reaching the flat area you hit the terrain, so keep altitude until you are above the segment.
- Using integer division in the braking angledx / speed with integers is 0 most of the time. Cast to double before calling asin.
Going further
A useful way to tune the thresholds instead of guessing is braking distance. At full power and tilt θ, the horizontal deceleration is 4·sin θ m/s², at most 4 m/s² when lying flat but then you fall, so in practice about 2 to 3 m/s². Stopping from a horizontal speed h needs roughly h² / (2a) metres: at 60 m/s and 2.5 m/s² that is about 720 m, which is why entering a 1000 m zone at more than about 60 m/s often overshoots. Checking 'distance to the far edge > h² / (2a) + margin' before committing to the descent is more robust than fixed speed bands, and it is the same reasoning you will need for Mars Lander Episode 3, where the zone is reached through caves and blind thresholds stop working.
FAQ
Why 21 degrees in Mars Lander?
acos(3.711 / 4) ≈ 21.9° is the largest tilt at which full thrust still cancels gravity, so the lander can move sideways without losing height. Rounding down to 21 keeps a small upward margin.
Is a genetic algorithm needed for Episode 2?
No. A rule-based controller like this one passes all tests. Genetic algorithms become attractive in Episode 3, where the terrain is much harsher.
Why does my lander crash with good speeds but a non-zero angle?
The angle must be exactly 0 on contact, and it can only change 15° per turn. Request 0° several turns before you reach the ground.