有这样一个题目:

Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]

For better understanding, please follow the numbers of the next array consecutively:

array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]

This image will illustrate things more clearly:

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as [[]]

题目意思是,给出一个N*N的二维数组,要求输出一个顺时针的一维数组,0*0的和1*1的直接原样一维数组返回就行了。

下面是我的解法:

snail = function (array) {
// enjoy
let len = array.length;
console.log(len);
if (array.length == 1) {
return array[0];
} else {
let i = 0, j = len - 1;
let rowStart = 1, rowEnd = len - 1, colStart = 0, colEnd = len - 2;
let direction = 'down';
for (let index = 0; index < len * (len - 1); index++) {
console.log(direction, 'direction');
switch (direction) {
case 'down':
i++;
if (i >= rowEnd) {
i = rowEnd;
rowEnd--;
console.log('down', i, rowEnd);
direction = 'left';
}
break;
case 'left':
j--;
if (j <= colStart) {
j = colStart;
colStart++;
console.log('left');
direction = 'up';
}
break;
case 'up':
i--;
if (i <= rowStart) {
i = rowStart;
rowStart++;
console.log('up');
direction = 'right';
}
break;
case 'right':
j++;
if (j >= colEnd) {
j = colEnd;
colEnd--;
console.log('right');
direction = 'down';
}
break;
}
console.log(array[i][j], i, j);
array[0].push(array[i][j]);
} }
return array[0];
}

  虽然感觉啰嗦,但是勉强实现了。

  下面看看得分最高的选手的代码:

snail = function (array) {
var result;
while (array.length) {
result = (result ? result.concat(array.shift()) : array.shift());
for (var i = 0; i < array.length; i++) {
result.push(array[i].pop());
}
row.result = result.concat((array.pop() || []).reverse());
for (var i = array.length - 1; i >= 0; i--) {
result.push(array[i].shift());
}
}
return result;
}

代码简单,清晰明了,充分调用了数组的各种方法,pop、shift、reverse等。

还有更简单的写法,原理大同小异,可能广大网友没怎么往下看或者觉得上面选手的代码更容易读懂的原因吧,得分不高,但是代码更是简练到了极致,欣赏一下代码的艺术吧。

const snail = function (array) {
const list = [];
while (array.length) {
list.push(...array.shift(), ...array.map(row => row.pop()));
array.reverse().map(row => row.reverse());
}
return list;
}

that's all,  thanks!

codewars贪吃蛇算法题目的更多相关文章

  1. 小项目特供 贪吃蛇游戏(基于C语言)

    C语言写贪吃蛇本来是打算去年暑假写的,结果因为ACM集训给耽搁了,因此借寒假的两天功夫写了这个贪吃蛇小项目,顺带把C语言重温了一次. 是发表博客的前一天开始写的,一共写了三个版本,第一天写了第一版,第 ...

  2. 浅析初等贪吃蛇AI算法

    作为小学期程序设计训练大作业的一部分,也是自己之前思考过的一个问题,终于利用小学期完成了贪吃蛇AI的一次尝试,下作一总结. 背景介绍: 首先,我针对贪吃蛇AI这一关键词在百度和google上尽心了检索 ...

  3. AI贪吃蛇前瞻——基于Dijkstra算法的最短路径问题

    在贪吃蛇流程结构优化之后,我又不满足于亲自操刀控制这条蠢蠢的蛇,干脆就让它升级成AI,我来看程序自己玩,哈哈. 一.Dijkstra算法原理 作为一种广为人知的单源最短路径算法,Dijkstra用于求 ...

  4. [LeetCode] Design Snake Game 设计贪吃蛇游戏

    Design a Snake game that is played on a device with screen size = width x height. Play the game onli ...

  5. AI贪吃蛇(二)

    前言 之前写过一篇关于贪吃蛇AI的博客,当时虽然取得了一些成果,但是也存在许多问题,所以最近又花了三天时间重新思考了一下.以下是之前博客存在的一些问题: 策略不对,只要存在找不到尾巴的情况就可能失败, ...

  6. 贪吃蛇的java代码分析(一)

    自我审视 最近自己学习java已经有了一个多月的时间,从一开始对变量常量的概念一无所知,到现在能勉强写几个小程序玩玩,已经有了长足的进步.今天没有去学习,学校里要进行毕业答辩和拍毕业照了,于是请了几天 ...

  7. 以小时候玩的贪吃蛇为例,对于Java图像界面的学习感悟

    简介 正文 01.JFrame是啥? 02.JPanel 03. KeyListener 04.Runnable 05.游戏Running 06.游戏初始类编写 07.main 简介: 一直以来用代码 ...

  8. 【BZOJ-4213】贪吃蛇 有上下界的费用流

    4213: 贪吃蛇 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 58  Solved: 24[Submit][Status][Discuss] Desc ...

  9. Android实现贪吃蛇游戏

    [绥江一百]http://www.sj100.net                                                  欢迎,进入绥江一百感谢点击[我的小网站,请大家多 ...

随机推荐

  1. 付费?是不可能的!20行Python代码实现一款永久免费PDF编辑工具

    PDF(Portable Document Format),中文名称便携文档格式是我们经常会接触到的一种文件格式,文献.文档…很多都是PDF格式.它以格式稳定的优势,使得我们在打印.分享.传输过程中能 ...

  2. “随手记”开发记录day13

    今天继续对我们的项目进行更改. 今天我们需要做的是增加“修改”功能.对于已经添加的记账记录,长按可以进行修改和删除的操作. 但是今天并没有完成……

  3. 【模式识别与机器学习】——PCA主成分分析

    基本思想 其基本思想就是设法提取数据的主成分(或者说是主要信息),然后摒弃冗余信息(或次要信息),从而达到压缩的目的.本文将从更深的层次上讨论PCA的原理,以及Kernel化的PCA. 引子 首先我们 ...

  4. Django-model查询[为空、由某字符串开头、由某字符串结尾、包含某字符串],__isnull、__starswith、__endswith、__contains

    使用属性+__isnull就可以判断此字段为空 a = DatasClass.objects.filter(name__isnull=True) 使用属性+__startswith可以判断属性由某字符 ...

  5. C#设计模式之2-抽象工厂模式

    抽象工厂模式(Abstract Factory Pattern) 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/391 ...

  6. C#LeetCode刷题之#278-第一个错误的版本(First Bad Version)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3985 访问. 你是产品经理,目前正在带领一个团队开发新的产品.不 ...

  7. Vuex mapMutation的基本使用

    mapMutation-store中的同步方法 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default n ...

  8. angular中阿里矢量图标使用

    <!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta ...

  9. Python日期时间(详细)

    获取当前时间戳 import time t = time.time() millis1 = int(t) print('10位时间戳:{}'.format(millis1)) millis2 = in ...

  10. 为什么LinkedList不建议使用for循环遍历,而使用iterator方式进行遍历,但ArrayList建议使用for循环进行遍历呢?

    如果使用for循环方式遍历链表,由于链表中元素是通过指针连接彼此的,不存在索引的概念,如果使用for循环方式遍历LinkedList,依次传入索引值,则就相当于每次都要将链表撸一遍. 如:在下面的这个 ...