Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Posters

Who's Online (0)

Powered by Vanilla. Made with Bootstrap.
Minicodingchallenge #1 (beginner)
  • sangf
    Posts: 203
    hey, i'm a bit bored so i'm going to try and start some small non-time-consuming coding challenges. Deque hosted a few of these at another forum and they were fun to participate in - let's see how it turns out here. the idea is simple, i post a challenge, you solve it using any language you like, after a couple of days i'll post my official solution and credit anyone that took part. there are no prizes, this is just for fun!

    Minicodingchallenge #1 - Calculator (beginner)

    for this challenge you need to create a basic interpreted calculator, it must accept an input line containing a simple expression supporting addition, subtraction, division and multiplication operations.

    example input #1 - single operations:


    10+10
    5*5
    10/2



    example input #2 - multiple operations:


    20/10*2+1
    10*10-5+2
    10+5+3/2*0



    example input #3 - multiple operations w/ brackets:


    (5*6)-(23/2)
    6-(20*(2 +4))+1
    (10+5/3)*5



    consider the three different input examples to be different levels, solve whichever you like. if people enter/enjoy these; i'll continue with some better/more interesting challenges. good luck =]
  • Deque
    Posts: 78
    Which is the nick I know you from?
    I don't think I will participate this time, but nice idea.
  • Sh3llc0d3
    Posts: 1,910
    I want to see input #3 handled by c++! I've seen examples of it done, but i'd be impressed if anyone did it on the fly.
  • Deque
    Posts: 78
    It is not that hard to do that for multiple operations with brackets. This would be Java. It is a bit sloppy, it doesn't check wether the input is correct and the design could be better. But just to prove the concept:

    public class Calculator {

    public static void main(String[] args) {
    String[] testinputs = { \"( 10+2 )*(2+3)\", \"((1+2) - (1+2))\",
    \"((1-1)/(2*2)) + 5\", \"5+5\", \"(1)\", \"3.5 - 1\" };

    for (String input : testinputs) {
    System.out.println(\"calculating \" + input);
    System.out.println(calculate(input));
    System.out.println(\"-----------\");
    }

    }

    private static double calculate(String input) {
    input = new String(removeSurroundingBrackets(input.toCharArray()));
    if (isNumber(input)) {
    return Double.parseDouble(input);
    }
    String[] parts = splitIntoParts(input);
    if (isNumber(parts[0]) && isNumber(parts[2])) {
    double result = operate(Double.parseDouble(parts[0]),
    Double.parseDouble(parts[2]), parts[1]);
    return result;
    }
    return operate(calculate(parts[0]), calculate(parts[2]), parts[1]);
    }

    private static double operate(double a, double b, String operator) {
    if (operator.equals(\"+\")) {
    return a + b;
    }
    if (operator.equals(\"-\")) {
    return a - b;
    }
    if (operator.equals(\"/\")) {
    return a / b;
    }
    if (operator.equals(\"*\")) {
    return a * b;
    }
    return 0;
    }

    private static boolean isNumber(String string) {
    try {
    Double.parseDouble(string);
    } catch (NumberFormatException e) {
    return false;
    }
    return true;
    }

    private static String[] splitIntoParts(String input) {
    StringBuilder[] parts = initParts();
    char[] in = input.toCharArray();
    int part = 0;
    int bracketsOpen = 0;

    for (int i = 0; i < in.length; i++) {
    char c = in[i];
    if (c == '(') {
    bracketsOpen++;
    } else if (c == ')') {
    bracketsOpen--;
    }

    if (!Character.isWhitespace(c)) {
    parts[part].append(c);

    if (bracketsOpen == 0 && !(i + 1 >= in.length)
    && !(isNumberOrDot(c) && isNumberOrDot(in[i + 1]))) {
    part++;
    }
    }

    }

    String[] result = new String[parts.length];
    for (int i = 0; i < result.length; i++) {
    result[i] = parts[i].toString();
    }
    return result;
    }

    private static boolean isNumberOrDot(char c) {
    return Character.isDigit(c) || c == '.';
    }

    private static char[] removeSurroundingBrackets(char[] a) {
    if (a[0] == '(') {
    int openBrackets = 0;
    for (int i = 0; i < a.length; i++) {
    if (a[i] == '(') {
    openBrackets++;
    } else if (a[i] == ')') {
    openBrackets--;
    }
    if (openBrackets == 0 && (i == a.length - 1)) {
    char[] r = new char[a.length - 2];
    for (int j = 1; j < a.length - 1; j++) {
    r[j - 1] = a[j];
    }
    return r;
    } else if (openBrackets == 0) {
    break;
    }
    }
    }
    return a;
    }

    private static StringBuilder[] initParts() {
    StringBuilder[] parts = new StringBuilder[3];
    for (int i = 0; i < parts.length; i++) {
    parts[i] = new StringBuilder();
    }
    return parts;
    }

    }


    And this is the output:
    calculating (10+2)*(2+3)
    60.0
    -----------
    calculating ((1+2) - (1+2))
    0.0
    -----------
    calculating ((1-1)/(2*2)) + 5
    5.0
    -----------
    calculating 5+5
    10.0
    -----------
    calculating (1)
    1.0
    -----------
    calculating 3.5 - 1
    2.5
    -----------


    Edit: For getting user input the main can be modified to this:

    public static void main(String[] args) {
    System.out.println(\"type in 'quit' to leave the program\n\");
    while (true) {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    System.out.println(\"Your input\");
    String input = scan.nextLine();
    if (input.equals(\"quit\")) {
    break;
    }
    try {
    double result = calculate(input);
    System.out.println(\"Result: \" + result + \"\n\");
    } catch (Exception e) {
    System.out.println(\"Your input was not correct\n\");
    }
    }
    }


    Negative numbers are not allowed, but you can use floating point numbers. For more operations than two you always have to use brackets. I.e. this is not allowed: 1 + 2 + 3, but this is: (1+2) + 3 or this: 1 + (2 + 3)
    Whitespaces are ignored.

    Like I said: It is a bit sloppy and not intended to be actually used. Just a prove of concept.
  • Xin
    Posts: 3,251
    Solution to number 1 in vb , havent finished for * / and - but its straightforward by what i have done on +.
    Public Class Form1
    Dim calc As String
    Dim n1() As String
    Dim ans As String
    Dim x1 As Integer
    Dim x2 As Integer
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    calc = TextBox1.Text
    If calc.Contains(\"+\") Then
    n1 = Microsoft.VisualBasic.Split(calc, \"+\", 2)


    x1 = (n1(0))
    x2 = (n1(1))
    ans = x1 + x2

    MessageBox.Show(ans)
    ElseIf calc.Contains(\"*\") Then
    End If

    End Sub
    End Class
    Xin
  • undead
    Posts: 822
    Solution for all challenges in python:
    #!/usr/bin/python

    print 'Press Ctrl&C to exit\n'

    while True:
    x = input('Enter operation: ')
    print 'Result:', x

    lol

    Example output:
    Press Ctrl&C to exit

    Enter operation: 10+10
    Result: 20
    Enter operation: 20/10*2+1
    Result: 5
    Enter operation: (5*6)-(23/2)
    Result: 19


    But if you want it more complex, for the first challenge it would be something like this:
    #!/usr/bin/python
    while True:
    op = raw_input(\"Enter operation: \")
    if op.find('+') != -1:
    sp = op.split('+')
    firstnumber = (sp)[0]
    secondnumber = (sp)[1]
    res = int(firstnumber)+int(secondnumber)
    print \"Result:\", res


    Output:
    Enter operation: 35+35
    Result: 70


    This code is only for addition but other operations would work in the same way as this.
  • GT3X
    Posts: 20
    i lol'd @python solution

    I already made something like this 1 year ago i think i gonna post a C++ solution these days
  • nu11byte
    Posts: 53
    Undead beat me to the Python joke one, so here's the Perl one. :)


    #!/usr/bin/perl

    print \"Enter your equation: \";
    $eq = <STDIN>;
    print eval $eq;
    $toMakeUserPressEnterToClose = <STDIN>;
  • Xin
    Posts: 3,251
    said:


    Undead beat me to the Python joke one, so here's the Perl one. :)


    #!/usr/bin/perl

    print \"Enter your equation: \";
    $eq = <STDIN>;
    print eval $eq;
    $toMakeUserPressEnterToClose = <STDIN>;



    Yeah lol now i come to think about it that can be done it nearly all languages.
    Xin