DEV Community

Cover image for Daily Challenge #277 - Over the Road
dev.to staff
dev.to staff

Posted on

Daily Challenge #277 - Over the Road

You've just moved into a perfectly straight street with exactly n identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this:

1|   |6
3|   |4
5|   |2

Evens increase on the right; odds decrease on the left. House numbers start at 1 and increase without gaps. When n = 3, 1 is opposite 6, 3 opposite 4, and 5 opposite 2.

Given your house number address and length of street n, give the house number on the opposite side of the street.

Examples

over_the_road(address, n)

over_the_road(1, 3) = 6
over_the_road(3, 3) = 4

Tests

over_the_road(3, 5)
over_the_road(7, 11)

Good luck!


This challenge comes from rge123 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

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

Discussion (5)

Collapse
peter279k profile image
peter279k

Simple solution:

<?php
function overTheRoad($address, $street){
  return $street*2 - $address + 1;
}

Here is sample picture to explain all of this:
img

Collapse
bubbler4 profile image
Bubbler • Edited

APL (using Dyalog APL):

   ⍝ left(⍺):address, right(⍵):n
   OverTheRoad ← {⍺-⍨1+2×⍵}
   1 OverTheRoad 3
6
   3 OverTheRoad 3
4
   3 OverTheRoad 5
8
   7 OverTheRoad 11
16

   ⍝ Short, "tacit" form
   OverTheRoad ← -⍨+1+⊢
   ⍝ Arithmetic automatically maps over multiple numbers!
   1 3 3 7 OverTheRoad 3 3 5 11
6 4 8 16

(Use the bookmarklet on this post to see the code with APL font and syntax highlighting.)

Explanation: The sum of two houses facing each other is always the same for given n, which is 2n+1. So the opposite house number becomes 2n+1-address.

Collapse
rafi993 profile image
Rafi

Ruby

def over_the_road(address, n)
    (n * 2) + 1 - address 
end
Collapse
savagepixie profile image
SavagePixie
const overTheRoad = (a, n) => 2 * n - a + 1
Collapse
citizen428 profile image
Michael Kohl

Postscript:

GS>/overTheRoad { 2 mul exch sub 1 add } def
GS>1 3 overTheRoad =
6
GS>3 3 overTheRoad =
4