3
\$\begingroup\$

I'm recieving 2-dimensional positions of two objects as a string with this format: x1,y1,x2,y2. The string is recieved from a readline call (replaced in the snippet with a prompt).

In order to get the horizontal and vertical position differentials, I'm writing the following code:

[x1,y1,x2,y2]=prompt("Please enter the positions separated by commas").split`,`
dx=+x2-x1
dy=+y2-y1
console.log(dx,dy)

Is there a way to get dx and dy using less characters since I don't really need the positions? I suppose the main problem could be in the variable assignment which can probably be done in one step. I can use ECMAScript 6.

I don't really know if I have to precise it but removing the text in the prompt or giving variables 1-char names doesn't count, I have written them on purpose to clarify my question. The console.log is not part of the code golf either since the variables are supposed to be used after in the program.

\$\endgroup\$
10
  • 1
    \$\begingroup\$ Welcome to Code Golf! Despite the close vote, I think you've already included the appropriate tags for such a question and this is indeed on-topic. \$\endgroup\$
    – Arnauld
    Commented Mar 7, 2020 at 11:51
  • 3
    \$\begingroup\$ I would appreciate if the people voting to close this could leave a comment. There is no way this user can improve the question without the necessary feedback. \$\endgroup\$
    – Wheat Wizard
    Commented Mar 7, 2020 at 13:02
  • 1
    \$\begingroup\$ Are you asking how to golf the middle two lines, specifically? Or the whole thing? \$\endgroup\$
    – Shaggy
    Commented Mar 7, 2020 at 13:08
  • 3
    \$\begingroup\$ Could you state in the question what requirements you have on the input and precisely? Also, it may not matter much here, but please state what version(s) you are limited to using. \$\endgroup\$ Commented Mar 7, 2020 at 15:38
  • 3
    \$\begingroup\$ So we recently adopted some new requirements for questions about golfing specific code, and your post already does a good job covering most of these. One remaining point is, what's the source or context for the challenge? Note also FryAmTheEggman's question on I/O. Also, I think it would help to edit your comment to Shaggy about your goal into the question itself. \$\endgroup\$
    – xnor
    Commented Mar 7, 2020 at 17:35

1 Answer 1

3
\$\begingroup\$

I'm not sure exactly what you're looking for, but perhaps something like this?

[x1,y1,dx,dy]=prompt("Please enter the positions separated by commas").split`,`
dx-=x1
dy-=y1
console.log(dx,dy)

Reusing x2 and y2 as dx and dy, respectively, lets you use the -= operator to shorten it a bit.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.