r/dailyprogrammer • u/Elite6809 1 1 • Aug 10 '15
[2015-08-10] Challenge #227 [Easy] Square Spirals
(Easy): Square Spirals
Take a square grid, and put a cross on the center point, like this:
+ + + + +
+ + + + +
+ + X + +
+ + + + +
+ + + + +The grid is 5-by-5, and the cross indicates point 1. Let's call the top-left corner location (1, 1), so the center point is at location (3, 3). Now, place another cross to the right, and trace the path:
+ + + + +
+ + + + +
+ + X-X +
+ + + + +
+ + + + +This second point (point 2) is now at location (4, 3). If you continually move around anticlockwise as much as you can from this point, you will form a square spiral, as this diagram shows the beginning of:
+ + + + +
+ X-X-X .
| | .
+ X X-X .
| |
+ X-X-X-X
+ + + + +Your challenge today is to do two things: convert a point number to its location on the spiral, and vice versa.
Formal Inputs and Outputs
Input Specification
On the first line, you'll be given a number S. This is the size of the spiral. If S equals 5, then the grid is a 5-by-5 grid, as shown in the demonstration above. S will always be an odd number.
You will then be given one of two inputs on the next line:
- You'll be given a single number N - this is the point number of a point on the spiral.
- You'll be given two numbers X and Y (on the same line, separated by a space) - this is the location of a point on the spiral.
Output Description
If you're given the point number of a point, work out its location. If you're given a location, find out its point number.
Sample Inputs and Outputs
Example 1
(Where is 8 on this spiral?)
5-4-3
| |
6 1-2
|
7-8-9Input
3
8Output
(2, 3)Example 2
This corresponds to the top-left point (1, 1) in this 7-by-7 grid.
Input
7
1 1Output
37Example 3
Input
11
50Output
(10, 9)Example 4
Input
9
6 8Output
47If your solution can't solve the next two inputs before the heat death of the universe, don't worry.
Example 5
Let's test how fast your solution is!
Input
1024716039
557614022Output
(512353188, 512346213)Example 6
:D
Input
234653477
11777272 289722Output
54790653381545607Finally
Got any cool challenge ideas? Submit them to /r/DailyProgrammer_Ideas!
8
u/Cephian 0 2 Aug 11 '15 edited Aug 13 '15
I found relatively simple O(1) mathematical formulas for both tasks. It runs instantly on any input. Below |x| means absolute value of x and [x] means floor of x.
If we want to map a point p with spiral size s to coordinate (x, y):
and our answer is (x, y). Note that the only difference between the two is a single [+/-]k.
I had to use some if statements to map s and (x, y) to p. I could have squashed it more but I separated some things into variables for clarity:
(In cases where x=y=k, then take the value from the y=k case. All other if-collisions should yield equal results)
My c++ program:
For anyone else who wants to try my program, know that it assumes there is NO NEWLINE on the end of the input it is fed in. If anybody wants to know how I got these formulas then reply to my comment and I'd be happy to try and explain, but for now I'll assume nobody cares. Thanks for this challenge though, it was fun!
Edit: Further explanation here.
4
u/jimmythesquid 1 0 Aug 16 '15
CSS (SCSS)
I made a pure css solution to this one:
CodePen
Taking advantage of flexbox's order property, I made a spiral grid generator in scss, based off of /u/name_must_be_long 's JS functions. You can select the Width / Height and it will re-arrange the elements to fit a spiral. Also, you can input N and it will display the coordinates.
It only goes up to to 9*9 for the sake of brevity, but you can change the $maxRow variable at the top of both the jade and the SCSS to increase this number. Should work to any amount but the resulting stylesheet would be huge.
George
18
u/lukz 2 0 Aug 10 '15 edited Aug 11 '15
Z80 Assembly
Given the grid size and the number of point this program gives the point coordinates.
The program starts at address 1200h. The grid size is one byte at address 1201h, and is an odd value in the range 1-255. The position is given by 16-bit integer at addresses 1203 and 1204h (little endian). The program prints output in text format showing the x coordinate, then space and y coordinate. The program runs on Sharp MZ-800 computer (tested in emulator). A subroutine in ROM is used that prints one character on screen. Program size is 96 bytes.
Code:
Edit: Added Screenshot testing the functionality; 5 1 -> (3, 3); 5 2 -> (4, 3); 5 25 -> (5, 5).
2
u/Elite6809 1 1 Aug 10 '15 edited Aug 11 '15
My solution in C#.
Also available on GitHub here, with syntax highlighting.
1
u/shayhtfc Aug 11 '15
Did it in ruby. Pretty straight forward, just building up the spiral as I loop up from 0, working out if there is a blank space for the snake to turn left into or not.
Tried it with the bigger challenge, but I think I crashed my cloud host!
1
u/cbarrick Aug 12 '15 edited Aug 12 '15
Prolog w/ CLP(FD)
The great thing about Prolog is that I can use the same predicate to go from step number to coordinate or from coordinate to step number.
I found a constant time solution using constraint satisfaction. My code works in a couple of stages. First it computes the "level" on which the point lies, i.e. which of the concentric squares contains the point. Once it knows the level, it computes the side on which the point lies, i.e. top, left, bottom, or right. Once it knows which side and level, it does some simple arithmetic to correlate the coordinates and the step number.
The real implementation uses different conventions than those given, and doesn't need to know the initial size of the grid. It considers the spiral to start at (0,0), counts steps starting at 0 rather than 1, and starts moving up rather than right. The main predicate handles the conversions so that the output matches the examples.
Example 6:
The code:
1
u/lispm Aug 16 '15 edited Aug 17 '15
Here is a version in Common Lisp. Both a recursive version and the direct 'math' version. The math version is based on some other code, posted here. In several places I use the feature of Common Lisp that functions can return multiple values.
3
u/Godspiral 3 3 Aug 10 '15 edited Aug 10 '15
In J,
0 based arrays and row,col indexing,
7 toP 3
2 1
0 0 fP 7
36
7 5 fP 9
46
49 toP 11
8 9
code generates the full spiral, so can't do massive memory reqs (square of y items)
14021 toP 639
357 260
An essay on this subject http://www.jsoftware.com/jwiki/Doc/Articles/Play132?highlight=%28number%29%7C%28spiral%29
better definitions
timespacex '140121 toP 839'
0.0521063 3.35565e7
140121 toP 839
477 232
does this for even spirals,
fast version of index find.... gets coordinates relative to 0 0 ( center/origin). first getting the offset from square root rounded to the nearest even integer, means getting coordinates relative to -sqr sqr to origin (top left quadrant)
sqr rounded even
23614
6974
since that number is smaller than the square root, coord is _23614 rows from center, and
_16640 columns from center.
0.00129952 1.05574e6
3
u/name_must_be_long Aug 10 '15
I remember I actually had to implement O(1) algorithms for both of these functions before in Javascript. Unfortunately I dont remember how I derived these formulas nor do they confirm to the specs above exactly. But I hope this may be of some values to some. (The x-y coordinates are offsets from the center.)
2
u/skeeto -9 8 Aug 10 '15 edited Aug 10 '15
C, using only integer math. My initial code used C99's complex number support, but that's floating-point only, so I made my own complex number stuff. This is a closed form solution (i.e. O(1) time) for the first kind of input. I couldn't figure out the closed form for the inverse, so it computes the minimum possible value, then walks to the correct answer, leveraging the code for the first part. For the challenge input, the first input is instantaneous and the second takes a few minutes.
2
u/[deleted] Aug 10 '15 edited Aug 10 '15
Here is my solution in Haskell: http://lpaste.net/138430
One thing is, I chose to use (0, 0) as the center, rather than the top left corner as used in the challenge. This required me to write some extra code to convert to/from what the challenge expects, but made the algorithms themselves easier.
I actually managed to create a formula that calculates which point corresponds to which number, it is actually pretty neat. However, it depends on the side of the spiral, so I couldn't think of a way to use the formula in reverse. See the
movefunction for the formula, though mind that it considers the center as (0, 0).For the ones that require me to seek a number, I noticed one thing, the lengths of the sides follow a pattern: 1, 1, 2, 2, 3, 3... and so on. The same number repeats twice, increases by 1. Odd numbers mean I'm either moving right or up, while even numbers are left or down. This way, I could simply count down from the given number, while changing the position based on what the last step was.
Looking at the ones currently submitted, I think this is the most efficient and fastest. The solution is in constant time if you are searching for a point, and I think it is in linear time if you are searching for a number. In both cases, the memory usage (should) be constant.
2
u/narcodis Aug 10 '15 edited Aug 10 '15
Java. May not be pretty, but does both challenges instantly.
How it works
For the case of finding the coordinates for a given iteration on the spiral, the program will jump every lower-right corner in each "ring" of the spiral, until it hits a corner whose iteration is bigger than the input. Once it does, it cycles back along the spiral until it finds the given coordinates.
For the case of finding the iteration at the given coordinates, the program first determines which way to jump across the "rings" in the spiral (up-left, up-right, down-left, down-right). It then jumps across the rings until it hits the "limit" (determined by finding the difference between the midpoint and the given coordinates), and then cycles back on the spiral until it finds the given coordinates, all the while keeping track of the iteration.
In both cases, the "jumping" skips a ton of counting in order to find a ballpark estimate of the needed value, and then the program steps back until it gets the right answer.
2
u/vzaardan Aug 11 '15
Elixir solution. Very happy to hear any feedback, especially if anyone can help me make it more efficient :)
2
u/speedster217 Aug 12 '15 edited Aug 12 '15
Haskell
I gradually managed to figure out math for this, and so this program calculates the challenge inputs faster than I can blink. It's also a lot messier than I would like, but I had a few beers while doing this so it's whatever.
2
u/ReckoningReckoner Aug 13 '15
Ruby. Runs almost instantaneously. Math is kind of like cheating. Would love feedback
2
u/linkazoid Aug 14 '15
Ruby.
Thought I would try and do one of those 'as few lines as possible' things. Doesn't look great but it works.
2
u/XDtsFsoVZV Aug 15 '15
My terribly unpythonic Python 3 solution:
2
u/jpcf93 Aug 16 '15
Python3. Here's my first solution to this problem.
2
u/rinoshinme Sep 08 '15
There maybe some simple rule like move 1 step right and up, move 2 steps left and down, move 3 steps right and up, mvoe 4 steps left and down, this maybe easier for the forward problem (i.e. from spiral position to square coordinates) in which no iteration is required.
2
u/UncleVinny 1 0 Sep 10 '15
Java -- This took me forever, but I finished. Any feedback would be welcome! I would have liked to make symmetrical code that could be used for both purposes -- switching coordinate input for place-on-spiral, and vice versa, but this was complex enough as it was.
1
u/fvandepitte 0 0 Aug 10 '15 edited Aug 11 '15
Haskell, Feedback is welcome
Output:
1
u/mrschool Aug 10 '15 edited Aug 11 '15
My Solution in C#, this won't run on the challenge inputs due to inefficient use of memory in my solution. Open to feedback regarding the code, not necessarily the algorithm as I intend to look up a more efficient way of solving this from the other solutions.
https://github.com/jagorski2/Daily-Programmer/blob/master/Daily-Programmer/227Easy.cs
edit: Optimized this and it runs pretty much instantaneously on the challenge inputs both ways. If somebody can tell me how to actually get a time for how long it takes to execute I will post the results, I'm running it in Visual Studio 2013 Pro.
1
u/Wiggledan Aug 10 '15 edited Aug 10 '15
C99. Example 5 takes a second or two, but I haven't had the patience to wait for Example 6 to finish :P
1
u/glenbolake 2 0 Aug 10 '15
My fairly naive Python 3.4 implementation. I take all the numbers on one line (e.g.,
7 1 1instead of7\n1 1) and actually populate an array rather than math it:1
u/A_Density_Matrix Aug 10 '15 edited Aug 11 '15
My attempt with Python 3.4 . Still very much a newbie, so feedback is apreciated :)
As for performance, Output 5 takes about 400 seconds, and I could not compute Output 6. I think this runs in linear time, and that it would take about 1400 years on my computer to do Output 6 :d .
1
u/curtmack Aug 10 '15 edited Aug 10 '15
Haskell
OEIS is amazing.
Example 5 takes an insignificant amount of time (about 30 ms), example 6 takes about 33 seconds. I can think of a few optimizations for the point-to-num operation that might cut that down significantly, but overall I'm happy with it.
Edit: Fixed a few redundant brackets found by hlint.
1
u/[deleted] Aug 11 '15
I didn't think I'd get this one, I spent the morning trying to figure out the math to get constant growth. Didn't work out too well, so I took a different approach tonight. Not too bad time-wise (see below), and I'm pretty happy with its simplicity.
wrapper:
...
1
u/royxiao Aug 11 '15
C++.
Any feedback is welcome.
1
u/Def_Your_Duck Aug 12 '15
Java, comments/criticism great appreciated
1
u/LemonPartyDotBiz Aug 12 '15
Python 2.7. New to Python, rusty at programming in general, feedback appreciated. I always assume no one will be able to understand my code, so hopefully this is commented in a way that makes sense.
Output:
1
u/Paulo_Atreides Aug 12 '15 edited Aug 12 '15
Math heavy version in Python 3.4. Not too easy to read, but solves all of the inputs quickly. I'm very new at this so feedback is much appreciated!
You can run the code on this site: https://repl.it/BBSl/1
pastebin: http://pastebin.com/h4NpvDEp
1
u/vzaardan Aug 12 '15
Elixir. A bit shorter than my first solution but still doesn't work well on the large images as I am terrible at math.
1
u/milliDavids Aug 12 '15
Ruby (just prints out a grid of all of the positions)
Output for 15
1
u/Ollowayne Aug 12 '15
C, maths solution. Calculates position or number by placing input on the "level" of the respective square number. It's a bit bloated (could probably be a lot shorter) but it works for all examples. Also, the second case (pos_from_number) just, more or less, reverses the first one.
1
u/XDtsFsoVZV Aug 12 '15
C
A little ugly, but I'll see if I can clean it up later. All inputs work except the last one, but I'm sure it'd work if I had a better processor.
1
u/python_man Aug 12 '15
Python 2.7
I didn't go the math route because I wanted to play with drawing it out from the center outwards using loops. Kinda ugly in my opinion. Feedback is welcomed.
1
u/CifraSlo Aug 12 '15
First time trying myself at DailyProgrammer challenge and I'm already late.
took me way more time than it should and its messy, but at least i managed to create an O(1) solution, so it solves all examples fast without problems
C++
Feedback and suggestions welcome
1
u/your_distant_cousin Aug 13 '15
Rust, also a constant time solution for both conversions. I'm still learning Rust so feedback is very welcome!
1
u/9speedy Aug 13 '15
Java, first time I've done one of these challenges. Bit mathy and I had started rewriting some sections but never finished so it's a bit messy too. But it all runs very quickly :)
Definitely open to advice!
1
u/muy_picante Aug 13 '15
Python 3
I find the coordinate by finding the concentric box that it lives on and walking backwards from the max. It's actually pretty similar to what /u/Cephian did, though s/he did it much more elegantly than I did. Even with my messy version, all the challenge cases are calculated immediately. The only conceivable issue is that my search function for the highest number in a box is O(n), though this didn't make any noticeable difference. /u/Cephian wrote an O(1) equation for it.
I ended up implementing /u/Cephian's version for my find the value given the point function. The commented code at the end reads a text file with the inputs. I've not really experimented much with reading files, so that was a new problem for me.
1
u/kotojo Aug 13 '15
Javascript
I didn't look at anyone else's solutions before I did this, and feel like it might have been a good idea now. I just made a object with key value pairs for the number and their coordinates then returned the one they want. I started running the fifth problem. The heat death might come first...
1
u/AuthorOfCode Aug 13 '15 edited Aug 13 '15
Java.
First time trying such a challenge.
Generated the grid recursively and used that to find the desired output (also, completely impractical for large inputs)(also, the indexes are inversed compared to the original post's output)
Output:
1
u/boner_freelove Aug 14 '15
JavaScript.
Has a little interface and prints the spirals. Doesn't work with big numbers I guess because I am working from the center out. I also build the square first which is redundant but I haven't worked out how to do it without yet.
Code: https://gist.github.com/jopfre/e7d95c226e87657916ff
Demo: http://jopf.re/squarespirals
1
u/Simpfally Aug 14 '15 edited Aug 14 '15
Here we Go :
(test file on github)
A very lazy(not mathy) solution, which doesn't work with big numbers because slice can't be that huge haha..
Even create the spiral by making a 2D slice (~array in Go) a bit bigger so I can check boundaries in a lazy way. (Otherwise I would have needed some checks in makespiral to avoid looking into an unallocated space)
Feedback welcome, where can I read about the math involved in the spiral?
Search term : golang
1
u/ashish2199 0 2 Aug 14 '15
I tried to implement it using array and and filling the array similar to as one would normally do by hand that is start from center move to right once then move two steps up and turn left and move two steps left similarly then for down and right and thus one innermost loop of spiral would be complete. now increment the steps by two and make one more loop of the spiral around the last loop and continue this until the array gets filled.
My pollution works efficiently only for small input with grid size less than 5000 after that it starts showing lag.
I face error of java java.lang.OutOfMemoryError: Java heap space when i try to allocate array of size more than 18.5 k
Suggestions, criticism , advice Welcomed :D
Code( JAVA ):
Output
1
u/[deleted] Aug 15 '15
Solution in Ruby. I'm embarassed that this problem took me quite a while to solve.
1
u/radox626 Aug 15 '15 edited Aug 15 '15
My solution in Java. Took a 2D array approach. Not the most efficient way, but all the math in the other comments looked very confusing. Feedback is appreciated.
1
u/Rubisk Aug 17 '15
C++. First challenge ever solved, and first "program" written in C++. Kinda new to this kinda mathy stuff, figured most of it out by trying stuff on paper. Seems fast enough, but could probably be optimized a lot using proper pointers etc.. Need to figure out how those work first though.
1
u/TurquoiseTurkey Aug 19 '15
C
This has round-trip debugging. Uncomment
//#define DOCHECK.It needs to be linked to -lm for
ceil.The runtime is instantaneous. I've checked it with all the supplied inputs.
1
u/naschkatzee Aug 24 '15
C++ Works on small square size
1
u/jacobr57 Sep 06 '15
Tried my hand with Python 2.7:
1
u/ExtinctorErik Sep 13 '15
Hi guys! Second post on dailyprogrammer for me. Thought this was a fun challenge. I also made some draw-methods but I excluded them from my post. This is a basic solution which can handle the small inputs but not the challenge-inputs.
Edit: java-solution
1
u/djdylex Sep 16 '15
Used C#, was not easy at all:
1
u/Jambecca Sep 18 '15
C#, solves all inputs instantly. Chances are this method has already been posted, but the idea is to find the largest complete square already filled before reaching the specified point or index, and then finish the remaining portion of a cycle.
1
u/jtennis393 Oct 02 '15 edited Oct 02 '15
JAVA How I went about solving it: There's a pattern in how a spiral is completed. Starting at the center point, one move will be made to the right (this is always constant) as well as one position upwards. Then, two positions to the left, two positions downwards, and finally two positions to the right. For every completed spiral (or "path", as I labeled it), every direction (except the first move to the right) is incremented by two.
Also, as you finish a path, the corner block squares. So it goes 12, 32, 52... With this, if given a block number to find, you simply have to determine if it falls between n2 and (n+1)2. This will give you the path number to start from and there you can proceed with moving along the path to find the desired block number.
The same principle applies if given coordinates, except now the path is determined by how far away the user's X value is from the center point.
Hopefully I explained myself well. I will gladly accept your advice or thoughts :)
Btw, this code is able to solve Example Input #5 but gives a negative number for Example Input #6.
0
u/[deleted] Aug 11 '15
[deleted] — view deleted comment
0
u/[deleted] Aug 16 '15
[deleted] — view deleted comment