DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #5 - Ten Minute Walk

Hey there, it's time to get moving.

Today’s challenge is modified from user @JKphobic on CodeWars:

You live in a city where all roads are laid out in a perfect grid. You have the unfortunate habit of arriving too early or too late to your appointments, so you decide to create a Walk Generating App.

Any time you press the button, it will send you an array of one-letter strings representing directions to walk (eg. [‘n’,’s’,’w’,’e’]). You always walk only a single block in a direction. It takes one minute to traverse one city block.

Create a program that will return an array of one-letter strings representing the walk. The program should accept input for the amount of time the user decides to walk and should bring the user back to their starting location.

I wish the streets in my town were structured like this, it would make driving so much easier.

Good luck, happy coding!


Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Latest comments (21)

Collapse
 
dimitrilahaye profile image
Dimitri Lahaye

During my reflexion about this challenge, I figured out that if input is an odd number, you will never be able to go back at your start position.

Here my JS implementation:

function direction(time) {
  if (time % 2 > 0) {
    throw 'You will never go back!!';
  }
  const ahead = Math.ceil(time/4),
    turn = Math.floor(time/4);
    return ('n'.repeat(ahead) + 'w'.repeat(turn) + 's'.repeat(ahead) + 'e'.repeat(turn)).split('');
}

// let's test it

try {
  console.log(direction(4)); // print ["n", "w", "s", "e"]
} catch (e) {
  console.log(e);
}

try {
  console.log(direction(1));
} catch (e) {
  console.log(e); // You will never go back!!
}

try {
  console.log(direction(3));
} catch (e) {
  console.log(e); // You will never go back!!
}
Collapse
 
figueroadavid profile image
David Figueroa

Powershell

I went the voluntary choice route with a voluntary initial route, and reversing it to get back.

function New-WalkPattern {
    [cmdletbinding()]
    param(
        [parameter(ValueFromPipelineByPropertyName)]
        [ValidateRange(4,30)]
        [int]$WalkTime = 14
    )

    if ($WalkTime % 2 -gt 0) {
        $WalkTime --
    }
    $WalkTimeArray = [char[]]::new($WalkTime)

    $LastDirection = 'x' #picking an invalid direction on purpose
    $UserSteps = $WalkTime / 2
    $ReverseStepTracker = -1

    $North   = [System.Management.Automation.Host.ChoiceDescription]::New('&North', 'Walk North')
    $East    = [System.Management.Automation.Host.ChoiceDescription]::New('&East', 'Walk East')
    $South   = [System.Management.Automation.Host.ChoiceDescription]::New('&South', 'Walk South')
    $West    = [System.Management.Automation.Host.ChoiceDescription]::New('&West', 'Walk West')
    $Options = [System.Management.Automation.Host.ChoiceDescription[]]($North, $East, $South, $West)
    $Title   = 'Which Direction'
    $Message = 'Pick a direction to walk'

    function Test-IfWalkDirectionIsRepeated {
        param(
            [string]$ThisDirection
        )
        if ($LastDirection -eq $ThisDirection) {
            Write-Warning -Message 'You cannot travel the same direction twice in a row!'
            $Result = $true
        }
        else {
            $LastDirection = $ThisDirection
            $Result = $false
        }
        return $Result
    }

    for ($i = 0; $i -lt $UserSteps; $i++) {
        $Result  = $host.ui.PromptForChoice($Title, $Message, $Options, 0)
        switch ($Result) {
            '0' {
                    if (Test-IfWalkDirectionIsRepeated -ThisDirection 'N')
                    {
                        $i ++
                        $ReverseStepTracker ++
                    }
                    else {
                        $WalkTimeArray[$i]  = 'N'
                        $WalkTimeArray[$ReverseStepTracker] = 'S'
                        $ReverseStepTracker --
                    }
                    break
            }
            '1' {
                    if (Test-IfWalkDirectionIsRepeated -ThisDirection 'E')
                    {
                        $i ++
                        $ReverseStepTracker ++
                    }
                    else {
                        $WalkTimeArray[$i]  = 'E'
                        $WalkTimeArray[$ReverseStepTracker] = 'W'
                        $ReverseStepTracker --
                    }
                    break
            }
            '2' {
                    if (Test-IfWalkDirectionIsRepeated -ThisDirection 'S')
                    {
                        $i ++
                        $ReverseStepTracker ++
                    }
                    else {
                        $WalkTimeArray[$i]  = 'S'
                        $WalkTimeArray[$ReverseStepTracker] = 'N'
                        $ReverseStepTracker --
                    }
                    break
            }
            '3' {
                    if (Test-IfWalkDirectionIsRepeated -ThisDirection 'W')
                    {
                        $i ++
                        $ReverseStepTracker ++
                    }
                    else {
                        $WalkTimeArray[$i]  = 'W'
                        $WalkTimeArray[$ReverseStepTracker] = 'E'
                        $ReverseStepTracker --
                    }
                    break
            }
        }

    }
    Write-Output $('Your walk path is: {0}' -f ($WalkTimeArray -join ','))
}
Collapse
 
margo1993 profile image
margo1993
type PersonPosition struct {
    xAxis int
    yAxis int
}

func GenerateWalk(minutes int) ([]string, error) {
    personPosition := PersonPosition{0, 0}
    var walkingRoute []string

    if minutes % 2 != 0 {
        return walkingRoute, errors.New("Minutes must be even number, otherwise you can't end on starting point")
    }

    rand.Seed(time.Now().UnixNano())
    directions := []string{"n", "s", "e", "w"}

    for i := 0; i < minutes; i++ {

        personYAxis := personPosition.yAxis
        personXAxis := personPosition.xAxis
        distanceFromHome := abs(personYAxis) + abs(personXAxis)
        timeToGoHome := minutes - i
        if personYAxis >= 0 && timeToGoHome  == distanceFromHome{
            directions = removeItemFromArray(directions, "n")
        }

        if personYAxis <= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "s")
        }

        if personXAxis >= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "e")
        }

        if personXAxis <= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "w")
        }

        direction := rand.Intn(len(directions))
        route := directions[direction]
        walkingRoute = append(walkingRoute, route)

        switch route {
        case "n":
            personPosition.yAxis += 1
        case "s":
            personPosition.yAxis -= 1
        case "e":
            personPosition.xAxis += 1
        case "w":
            personPosition.xAxis -= 1
        }
    }

    return walkingRoute, nil
}

func removeItemFromArray(array []string, item string) []string {
    for i,  v:= range array {
        if v == item {
            return append(array[:i], array[i+1:]...)
        }
    }
    return array
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
Collapse
 
kesprit profile image
kesprit

My solution in Swift language :

func generateMinutesWalk(minutes: Int) -> [String]? {
    guard minutes % 2 == 0 else {
        print("Minutes is odd")
        return nil
    }

    let coordinates = ["N", "O", "S", "E"]
    var travel = [String]()

    for _ in 0..<minutes / 2 {
        travel.append(coordinates[Int.random(in: 0..<coordinates.count)])
    }
    travel.forEach { value in
        if let index = coordinates.firstIndex(of: value) {
            travel.append(coordinates[(index + 2) % coordinates.count])
        }
    }

    return travel
}
Collapse
 
celyes profile image
Ilyes Chouia

PHP


function take_a_walk(int $distance){

    if($distance %2 == 1){ 
        throw new Exception("take an even number of steps or no return home! <br>");
    }
    $steps = [];
    $directions = ['n', 'e', 's', 'w'];
    for($i = 1; $i <= $distance; $i+=2){
        $index = array_rand($directions);
        $steps[] = $directions[$index];
        $steps[] = $directions[($index + 2) %4];
    }
    shuffle($steps);
    $steps = implode(', ', $steps) . PHP_EOL;
    return $steps;
}
echo "Steps to take : " . take_a_walk(58);

Collapse
 
gnsp profile image
Ganesh Prasad
const generate = mins => isNaN(mins) || Number(mins) % 2 !== 0 ? null
    : Array(Number(mins)/2).fill('ns').join('');
Collapse
 
jasman7799 profile image
Jarod Smith
// in general we will create a sequence which just retraces itself after a certain time.
function generateWalkSequence(time) {
  if(time % 2 != 0) 
    throw new Error('Time must be even');
  let walkSequence = [];
  let oppositeDirections = [];
  let nextDirection = 'n';
  const directions = [...'nswe'];
  for(let i = 0; i < time/2; i++) {
    // loop selection after index 3
    walkSequence[i] = (nextDirection = directions[i % 4]);
    oppositeDirections[i] = (getComplement(nextDirection));
  }
  return [...walkSequence,...oppositeDirections.reverse()];
}

function getComplement(direction) {
  switch (direction) {
    case 'n':
      return 's';
    case 's':
      return 'n';
    case 'e':
      return 'w';
    case 'w':
      return 'e';
  }
}
Collapse
 
v613 profile image
Ceban Dumitru • Edited

BASH

#!/bin/bash
declare gps=(n s e w);
if [[ $((${1} % 2 )) = 0 ]]; then
    for (( i = ${1}; i >= 0; i-=2 )); do
        echo ${gps[$(($RANDOM%3))]};
    done;
else 
    echo "Sorry, you cannot generate way";
fi
Collapse
 
martyhimmel profile image
Martin Himmel

PHP

function go_for_a_walk(int $distance) {
    if ($distance % 2 == 1) {
        throw new Exception("There's no place like home. Unfortunately, you won't return home with an odd number of steps.");
    }

    $steps = [];
    $directions = ['n', 'e', 's', 'w'];
    while ($distance > 0) {
        $index = array_rand($directions);
        $steps[] = $directions[$index];
        $steps[] = $directions[($index + 2) % 4];
        $distance -= 2;
    }
    shuffle($steps);
    return $steps;
}

echo implode(', ', go_for_a_walk(10)) . PHP_EOL;

Some comments may only be visible to logged-in visitors. Sign in to view all comments.