Don't use images as main content of your post. This makes your question impossible to search and inaccessible to the visually impaired; we don't like that. Please transcribe text and mathematics (note that you can use LaTeX) and don't forget to give proper attribution to your sources!
– RaphaelNov 07 '17 at 20:37
Please get rid of the source code and replace it with ideas, pseudo code and arguments of correctness. See here and here for related meta discussions.
– RaphaelNov 07 '17 at 20:37
What have you tried? Where did you get stuck? We do not want to just hand you the solution; we want you to gain understanding. However, as it is we do not know what your underlying problem is, so we can not begin to help. See here for tips on asking questions about exercise problems. If you are uncertain how to improve your question, why not ask around in [chat]?
– RaphaelNov 07 '17 at 20:37