如何检查长生不老药中数组的元素是否按顺序排列 [英] How to check if the elements of an array are in sequential order in elixir

查看:39
本文介绍了如何检查长生不老药中数组的元素是否按顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在elixir中数组的元素是否按顺序排列.我到目前为止所拥有的

I want to know if the elements of an array are in sequential order in elixir. What I have so far

arr=[4,2,3,1]
arr2=[3,8,1,7]


Enum.each arr2, fn(x) ->

end

如果要按顺序打印,我想打印true.在这种情况下,这是正确的,因为arr1是按顺序排列的.Arr2将打印false,因为它不是按顺序排列的.我一直在努力解决这个问题,因为长生不老药中没有循环.

I want to print true if it is in sequential order. In this case it would be true since arr1 is in sequential order. Arr2 would print false since its not in sequential order. I have struggled with figuring this out as there are no loops in elixir.

推荐答案

您可以通过编写自己的简短递归函数来处理它,即:

You can handle it by writing your own short recursive function, ie:

  def check([_x]), do: true
  def check([head | tail]) do
    if head < hd(tail), do: check(tail),
    else: false
  end

我敢肯定,它甚至可以比这更短/更容易:)只需在其中传递您的列表即可(请记住,Elixir中没有数组):

I'm pretty sure it can be even done even shorter/easier than this :) Just pass your lists in there (please bear in mind that there are no arrays in Elixir):

list1 = [1,2,3,1,5]
list2 = [1,2,3,4,5]

iex()> check(list1)
false

iex()> check(list2)
true

但是,正如Aleksei在其中的一条评论中所写-尝试自己解决类似的难题是非常有益的;)我建议在 codewars :)祝你好运!

However, as Aleksei wrote in one of the comments - it's very beneficial to try to solve puzzles like that by yourself ;) I recommend playing with Elixir at codewars :) Good luck!

PS

如果您需要我的实施说明,请告诉我.

Please let me know if you would need an explanation of my implementation.

这篇关于如何检查长生不老药中数组的元素是否按顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆