DEV Community

dev.to staff
dev.to staff

Posted on

6

Daily Challenge #122 - Clockwise Spirals

Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional array with numbers 1 through NxN represented as a clockwise spiral.

Return an empty array if N < 1 or N is not int / number

Examples:

N = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]

1 2 3

8 9 4

7 6 5

N = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

N = 5 Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]

1 2 3 4 5

16 17 18 19 6

15 24 25 20 7

14 23 22 21 8

13 12 11 10 9


This challenge comes from alex.budiakov 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!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
idanarye profile image
Idan Arye • Edited

Rust:

fn create_spiral(diameter: usize) -> Vec<Vec<usize>> {
    let move_pos = |pos: [isize; 2], direction: [isize; 2]| [
        pos[0] + direction[0],
        pos[1] + direction[1],
    ];

    let mut result = vec![vec![0; diameter]; diameter];
    let mut pos = [0, 0];
    let directions = [
        [1, 0],
        [0, 1],
        [-1, 0],
        [0, -1]
    ];

    let mut direction = 0;
    for i in 1..=diameter.pow(2) {
        result[pos[1] as usize][pos[0] as usize] = i;
        let new_pos = move_pos(pos, directions[direction]);
        let should_turn =
            new_pos[0] < 0 || new_pos[1] < 0 ||
            diameter <= new_pos[0] as usize || diameter <= new_pos[1] as usize ||
            result[new_pos[1] as usize][new_pos[0] as usize] != 0;
        if should_turn {
            direction = (direction + 1) % directions.len();
            pos = move_pos(pos, directions[direction]);
        } else {
            pos = new_pos;
        }
    }
    result
}

fn main() {
    for row in create_spiral(10) {
        for cell in row {
            print!("{:4}", cell);
        }
        println!();
    }
}

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay