Coding Challenge #5: Sort and Maths
-
FUZE coding challenge #5
Hi everyone! Welcome to challenge #5 of the coding challenge series.
The rules are:-
Post your Fuze code below, not the project ID.
-
There will be 2 tasks per challenge, a Beginners challenge and an Advanced challenge. Anyone can participate in one or both tasks.
-
We are always open to suggestions!
-
Have fun coding!!
TASK #1
LEVEL: Beginner
Given an array of random numbers. Sort the Array from lowest to highest.
Example: [4,5,3,56,34,22,12] -> [3,4,5,12,22,34,56]TASK #2
LEVEL: Advanced
Given a string of math expressions, write a function that computes the sum of the string expression and return the result as an integer/float.
The expression could be as easy or as complex as you like it to be including "()".
Example:
"4 + 2 * 5" -> 14
"(5 - 3) * 4" -> 8 -
-
I will post a little selection sort implementation I have handy:
function sortList(list) sorted = list imin=0 swap = 0 /* assume smallest element value */ for i=0 to len(sorted)-1 loop imin=i for j=i+1 to len(sorted) loop if sorted[j] < sorted[imin] then imin=j endif repeat if imin!= i then swap = sorted[j] sorted[i] = sorted[imin] sorted[imin] = swap endif repeat return sorted
-
For Task #2, I did an implementation of the shunting yard method. It can evaluate valid infix expressions and it will evaluate invalid ones too since there is no validity checking.
Function Eval(Expr) var OpChar = [ "(", "*", "+", "-", ")" ] var OpPrec = [ 4, 3, 2, 2, 1 ] float VS[0] int TopVS = 0 // Value Stack int OS[0] int TopOS = 0 // Operator Stack Expr += "+0" // This makes it finish up the stuff on int I // the stack when it gets to the end For I = 0 To Len(Expr) Loop int J = ChrVal(Expr[I]) - ChrVal("(") If J < 64 And 1 << J & 0x2F Then // Expr[I] ~ "()+-*" J = [ 0, 4, 1, 2, -1, 3 ][J] // Remap the character code While TopOS > 0 Loop If OpPrec[J] > OpPrec[OS[TopOS - 1]] Then Break EndIf If OpChar[OS[TopOS - 1]] == "(" Then TopOS -= OpChar[J] == ")" // Pop matching '()' Break EndIf TopOS -= 1 // Evaluate the operator on top If OpChar[OS[TopOS]] == "+" Then TopVS -= 1 VS[TopVS - 1] += VS[TopVS] EndIf If OpChar[OS[TopOS]] == "-" Then TopVS -= 1 VS[TopVS - 1] -= VS[TopVS] EndIf If OpChar[OS[TopOS]] == "*" Then TopVS -= 1 VS[TopVS - 1] *= VS[TopVS] EndIf Repeat If OpChar[J] != ")" Then OS[TopOS] = J TopOS += 1 EndIf Else int J For J = I To Len(Expr) Loop int N = ChrVal(Expr[J]) - 46 // Expr[J] !~ ".0123456789" If N > 63 Or 1 << N & 0xFFD == 0 Then Break EndIf Repeat If J > I Then // It is a Number J -= 1 VS[TopVS] = Float(Expr[I: J]) TopVS += 1 I = J EndIf EndIf Repeat Return VS[0]