Fish, cetaceans and many other aquatic vertebrates undulate their bodies to propel themselves through water. Numerous studies on natural, artificial or analogous swimmers are dedicated to reveal the links between the kinematics of body oscillation and the thrust production to swim. One of the most open and difficult question is what is the best kinematics to maximize this quantity for given constraints and how a system strategizes and adjusts its internal parameters to reach this maximum. To address this challenge, we exploit a biomimetic robotic swimmer to determine the control that produces the highest thrust. Using machine learning techniques and intuitive models, we uncover that this optimal control consists of a square wave function, whose frequency is fixed by the interplay between the internal dynamics of the swimmer and the fluid-structure interaction with the surrounding fluid. We then propose a simple implementation for autonomous robotic swimmers that requires no prior knowledge of systems or equations. This application to aquatic locomotion is validated by 2D numerical simulations.