HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Erlang treasure hunt

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hunterlangtreasure

Problem

I have the following task:


Create a simple treasure hunt game.


Create a two-dimensional array of integers 10 by 10. In a random
position in the array store the number 1. repeat Get the user to
enter coordinates where they think the treasure is. If there is a 1
at this position display ‘success’. Until they find the treasure

Instead of using arrays I used lists:

-module(hunt).
-export([start/0]).
start() -> 
    X = [[12,1,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5]],
    loop(X).
loop(X) ->
    Inputs = io:get_line("Enter the coordinates"),
    {A,_} = string:to_integer(string:substr(Inputs,1,2)),
    {B,_} = string:to_integer(string:substr(Inputs,3,2)),
    erlang:display(A),
    erlang:display(B),
    case get(X,A,B) of
        1 -> io:format("You did it!");
        _ -> io:format("Try again"), loop(X)
    end.
get(List,A,B) ->
    ghelper(List,A,B).
ghelper(List,A,B) -> ghelper(List,A,B,0,0).
ghelper([H|Tail],A,B,N,M) -> 
    case N == A of
        true -> ghelper(second,H,B,M);
        false -> ghelper(Tail,A,B,N+1,M)
    end.
ghelper(second,[H|Tail],B,M) -> 
    case M == B of
        true -> H;
        false -> ghelper(second,Tail,B,M+1)
    end.


Is there a way to improve this further? I know I could probably make a function to randomly generate a 2D array (represented by lists here), but apart from that, is there anything I could improve?

Solution

Even though your code works I have some comments regarding Erlang style and naming conventions:

  • Spaces after commas and empty lines between function definitions make the code a lot more readable.



  • Helper functions that do the actual work are usually named with the do_ prefix. Instead of ghelper I would have named that do_get.



  • Using lists:nth could greatly simplify your code. The standard library includes a lot of useful functions, I try to always check if there is an existing function for what I want to do and only if there's none then I implement it.

Context

StackExchange Code Review Q#96020, answer score: 3

Revisions (0)

No revisions yet.