Sounds like it could be framed as a linear programming problem (minimize the amount of material thrown away). Perhaps limit the length of each rail, and bound the number of each size based upon your...