这是一个ump撞的词吗?


31

(受难题上的挑战启发- 该难题的SPOILERS在下面,因此如果您想自己解决难题,请在这里停止阅读!)

如果单词中的字母在字母上出现的时间晚于单词中的前一个字母,我们称这为两个字母之间的上升。否则,包括同一个字母在内,就称为坠落

例如,单词ACE有两个上升(Ato CCto E)并且没有下降,而THE有两个下降(Tto HHto E)并且没有上升。

如果上升和下降的顺序交替出现,我们将其称为“ 颠簸”。例如,BUMP上升(BU),下降(UM),上升(MP)。请注意,第一个序列不必是上升- BALD下降-下降-下降,并且也是颠簸的。

挑战

给定一个单词,输出是否为Bumpy。

输入值

  • 仅由ASCII字母([A-Z]任何形式)组成的单词(不一定是词典单词)。[a-z]
  • 您选择输入是全部大写还是全部小写,但必须一致。
  • 该单词的长度至少为3个字符。

输出量

输入的单词是Bumpy(真)还是Bumpy(假)的真实/假值。

规则

  • 完整的程序或功能都是可以接受的。
  • 禁止出现标准漏洞
  • 这是因此所有常见的高​​尔夫规则都适用,并且最短的代码(以字节为单位)获胜。

例子

真相:

ABA
ABB
BAB
BUMP
BALD
BALDY
UPWARD
EXAMINATION
AZBYCXDWEVFUGTHSIRJQKPLOMN

虚假:

AAA
BBA
ACE
THE
BUMPY
BALDING
ABCDEFGHIJKLMNOPQRSTUVWXYZ

排行榜

这是一个堆栈片段,用于按语言生成常规排行榜和获胜者概述。

为确保您的答案显示出来,请使用以下Markdown模板以标题开头。

# Language Name, N bytes

N您提交的文件大小在哪里。如果您提高了分数,则可以将旧分数保留在标题中,方法是将它们打掉。例如:

# Ruby, <s>104</s> <s>101</s> 96 bytes

如果要在标头中包含多个数字(例如,因为您的分数是两个文件的总和,或者您想单独列出解释器标志罚分),请确保实际分数是标头中的最后一个数字:

# Perl, 43 + 2 (-p flag) = 45 bytes

您还可以将语言名称设置为链接,然后该链接将显示在页首横幅代码段中:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes


该死的。如果同一封信既不升不降,则更容易。
mbomb007'9

我不理解所提供的示例:如果BUMP在Truthy(即Bumpy)中列出,为什么BUMPY在Falsey列表中?“起伏交替”是什么意思?两个上升不能连续吗?
VolAnd

4
@VolAnd是的,这意味着上升之后总是下降,反之亦然。BUMPY是虚假的,因为MPY连续两次上升。换句话说,对于单词颠簸而言,长度3的子字符串都不必升序或降序排序(除了两个连续字母相同的特殊情况)。
马丁·恩德

您可以破坏Puzzling.SE问题的答案,以便其他希望自己解决的人可以这样做吗?
OldBunny2800'9

1
@ OldBunny2800我不会放一个完整的剧透(我不想在这里通过隐藏关键信息来使我的挑战难以阅读),但是我会在顶部添加一些其他文字作为警告。谢谢!
AdmBorkBork

Answers:


31

MATL,4个字节

d0>d

说明:

d     % Implicitly take input. Take difference between each element
 0>   % Check whether diff's are positive. Should result in [0 1 0 1 ...] pattern.
   d  % Again take the difference. Any consecutive rises or falls results in a 
      % difference of 0, which is a falsy value in MATL

这是我的第一个MATL条目,因此我想知道从我的MATLAB / Octave尝试中的这个天真的端口可以得到多少改进@(a)all(diff(diff(a)>0))。请注意,这all不是必需的,因为任何零都会使数组为假,因此AMATL端口中没有。


查看更正后的挑战。一个测试用例中有一个错字。您的方法是正确的。实际上,d0>d应该可以工作(A根据我们对真假的定义,您不需要)
Luis

1
做得好,用自己的语言超越路易斯!我以前尝试过,但这不是一件容易的事。;)
DJMcMayhem

@DJMcMayhem哈哈。这就是我过快地阅读挑战所获得的。在我的辩护中,两个相等的字母为秋天是违反直觉的。并且(已更正)具有误导性的测试用例也无济于事:-)
Luis Mendo

1
@DJMcMayhem谢谢-虽然也许我只是很幸运,因为我实际上没有考虑连续的等号,但是事实恰恰是所要的……
Sanchises

1
@immibis是在MATL(AB)和Octave中。看到这个元答案。
桑契斯

24

JavaScript(ES6),75 69 63 46 43字节

感谢Neil,节省了3个字节:

f=([c,...s])=>s[1]?c<s[0]^s[0]<s[1]&&f(s):1

解构string参数而不是s.slice(1)


先前的解决方案:
由于ETHproductions,节省了17个字节:

f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1

从先前的解决方案逐步得出的结果是:

f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b // (63) Original
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(s[i]<s[i+1]))?f(s,i):b   // (61) No point in reassigning `a`, it's not used again
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^s[i]<s[i+1])?f(s,i):b     // (59) Remove unnecessary parentheses
f=(s,i=0)=>s[i+2]&&(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b         // (55) `a` is now just a waste of bytes
f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b:1        // (56) Rearrange conditional expressions to allow for more golfing
f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1         // (55) Rearrange conditional expression
f=(s,i=0)=>s[i+2]?(s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1           // (53) `b` is now also a waste of bytes
f=(s,i=0)=>s[i+2]?s[i++]<s[i]^s[i]<s[i+1]&&f(s,i):1             // (51) Remove unnecessary parentheses
f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1                  // (46) Use `s.slice(1)` instead of `i`


先前的解决方案:
由于ETHproductions而获得了63个字节:

f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b

69个字节:

f=(s,i=0,a=s[i++]<s[i])=>i+1<s.length&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b

75个字节:

f=(s,a=s[0]<s[1])=>{for(i=1;i+1<s.length&&(b=a^(a=s[i++]<s[i])););return b}

单词中的所有字母必须具有相同的大小写。



@ETHproductions我应该发布您链接的内容吗?
Hedi

如果您愿意的话,您可以:-)
ETHproductions's

可以!s[2]|...做一样s[2]?...:1吗?
泰特斯(Titus)

1
抱歉,聚会晚了,但有43个字节,我给您:f=([c,...s])=>s[1]?c<s[0]^s[0]<s[1]&&f(s):1
尼尔

14

LabVIEW,36个等效字节

使用逻辑等价向下打:

golfed

取消高尔夫:

ungolfed

首先,我们转换为小写字母,然后转换为字节数组。修剪掉字节数组的第一个元素,因为它没有先例。然后,对于数组中的每个元素,检查其是否大于上一个元素(U8 char映射为您所期望的ASCII),并存储下一次迭代的结果,以及存储在数组中以查看整体凹凸。如果当前和先前的布尔检查相等,则我们终止循环,并且不会遇到麻烦。否则,它很颠簸!


1
多么酷的语言!欢迎来到PPCG!
DJMcMayhem

1
谢谢!我永远不会与4字节的答案竞争,但这是提高我的技能的好方法:)
ijustlovemath 16/09/13

这里。您的计分绝对错误的,并且过于夸张。我认为您的答案实际上不是246450-246549字节。
暴民埃里克(Erik the Outgolfer)

我不打算使用“内存”选项卡,因为我不知道LabVIEW是否有等效字节的概念。今天晚些时候将对他们进行计数并编辑答案。
ijustlovemath 16/09/13

1
@Erik我在Windows上的Firefox上运行,但在移动设备上打开它也会使事情中断。只是meta.ppcg.lol起作用。无论如何,这超出了评论的范围。
基金莫妮卡的诉讼

8

Python,56个字节

lambda s:all((x<y)^(y<z)for x,y,z in zip(s,s[1:],s[2:]))

所有测试用例都在ideone上

通过s中的字符三元组进行齐整,并测试所有这些三元组具有左右对,它们的上升/下降特性不同。
适用于全部大写或全部小写。


6

Ruby,57个48字节

期望输入全部为大写。

->s{!s.gsub(/.(?=(.)(.))/){($&<$1)^($1<$2)}[?f]}

在repl.it上查看:https ://repl.it/D7SB

说明

正则表达式/.(?=(.)(.))/匹配每个字符,然后再跟两个字符。(?=...)是一个积极的前瞻,这意味着我们匹配后两个字符,但不要将它们“消耗”为匹配的一部分。大括号内$&是匹配的文本(三个中的第一个字符),而$1and $2是前行中捕获的字符。换句话说,如果字符串是"BUMPY",它将首先匹配"B"(并将其放入$&)并捕获"U""M"(并将其放入$1$2)。接下来,它将匹配"U"并捕获"M""P",依此类推。

块内我们检查,如果第一对字符($&$1)是一个上升和第二($1$2)是下降,或者反之亦然,就像大多数其他的答案。此^表达式返回truefalse,该表达式将转换为字符串并插入匹配项。结果,我们的示例"BUMPY"变为:

"truetruefalsePY"

由于我们知道输入全部为大写,因此我们"f"只知道部分输入是大写的,"false"!result[?f]给出了答案。


它是如何工作的?
GreenAsJade

1
@GreenAsJade我在回答中添加了解释。
约旦

6

C#,64 63 55字节

unsafe bool B(char*s)=>1>s[2]||*s<s[1]!=*++s<s[1]&B(s);

Scepheo建议的-8个字节

这是Hedi解决 C#问题的方法。我也想出了一个递归的解决方案,但是递归并不是那么好。我的原始解决方案如下。

我的原始C#,96 94 91字节

unsafe bool B(char*s,bool f=1>0,int i=0)=>1>s[1]||(s[0]<s[1]?f:1>i?!(f=!f):!f)&B(s+1,!f,1);

使用-2个字节1>0代替true

Scepheo对上述端口解决方案的建议中包含-3个字节

调用自己以递归方式检查每次上升/下降交替的时间。

取消高尔夫:

// unsafe in order to golf some bytes from string operations.
// f alternates with each recursive call
// i is 0 for the first call, 1 for all subsequent calls
unsafe bool B(char* s, bool f = 1 > 0, int i = 0) =>
    1 > s[1] ? 1 > 0// (instead of 1 == s.Length) check if s[1] = NULL, and return true.
    : (
        s[0] < s[1] ? f // Rising, so use f...
        : // Else falling
            1 > i ? !(f=!f) // But this is the first call, so use true (but flip f)...
            : !f // Not first call, so use !f...
    )
    & B(s+1, !f, 1) // ...AND the previous value with a recursive call
                    // s+1 instead of s.Substring(1)
;

似乎最后一个不需要?:操作符或括号即可:unsafe bool B(char*s)=>1>s[2]|s[0]<s[1]!=s[1]<s[2]&B(s+1);
Scepheo

实际上,尽管我无法对此进行测试,但是操纵指针本身似乎更加麻烦:unsafe bool B(char*s)=>1>s[2]|*s<s[1]!=*++s<s[1]&B(s);
Scepheo

@Scepheo我得到了那些建议的StackOverflowExceptions,但是它们使用布尔OR ||而不是按位OR进行工作|。更新了帖子,谢谢。
牛奶

6

C 59字节

r;f(s)char*s;{for(r=0;r=*s?~r&1<<(*s>=*++s):0;);return!*s;}

70字节的解决方案针对大小写返回1(真)AAA-示例中的第一个“ Falsey”
VolAnd

我正在使用进行测试,gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)而我对Aaa的判断却是错误的,并为此感到兴奋。在此版本中,非零为假,零为真。实际上,现在想知道是否允许这样做。
cleblanc

f("ABCDEFGHIJKLMNOPQRSTUVWXYZ")在Visual Studio 2012中编译的调用返回的值23可以视为,True但在问题中该值位于“ Falsey”部分中,因此0应为预期值。
VolAnd

我误解了对真假的允许。现在,我已经阅读了该文章,并且似乎很清楚“ C”的值必须是什么。
cleblanc

这是我们对真假的标准定义基于Meta共识的。
AdmBorkBork

5

果冻,6个字节

OI>0IẠ

基于@sanchises' answer.

在线尝试!要么Verify all.

说明

OI>0IẠ  Input: string S
O       Convert each char in S to an ordinal
 I      Get the increments between each pair
  >0    Test if each is positive, 1 if true else 0
    I   Get the increments between each pair
     Ạ  Test if the list doesn't contain a zero, 1 if true else 0


5

Python 2, 88 bytes

Simple solution.

s=input()
m=map(lambda x,y:y>x,s[:-1],s[1:])
print all(x-y for x,y in zip(m[:-1],m[1:]))

Try it online

If same letters in a row were neither a rise nor a fall, the solution would be 79 bytes:

s=input()
m=map(cmp,s[:-1],s[1:])
print all(x-y for x,y in zip(m[:-1],m[1:]))

5

Perl, 34 bytes

Includes +3 for -p (code contains ' so -e can't be used)

Give uppercase input on STDIN:

bump.pl <<< AAA

bump.pl

#!/usr/bin/perl -p
s%.%$&.z lt$'|0%eg;$_=!/(.)\1./

5

Python, 51 bytes

g=lambda a,b,c,*s:((a<b)^(b<c))*(s==()or g(b,c,*s))

Takes input like g('B','U','M','P') and outputs 1 or 0.

Uses argument unpacking to take the first three letters and check if the first two compare differently from the second two. Then, recurses on the remainder, using multiplication for and.


Nice input golf. ;-)
AdmBorkBork

5

Jelly, 6 5 bytes

-1 byte thanks to @Dennis (use a cumulative reduction)

<2\IẠ

All test cases are at TryItOnline

How?

<2\IẠ - main link takes an argument, s,    e.g. "BUMP"    or "BUMPY"
<    - less than comparison (a dyad)
 2   - literal 2 (a nilad)
  \  - n-wise overlapping reduction when preceded by a dyad-nilad chain
       (i.e. reduce the list by pairs with less than)
                                           e.g. [1,0,1]   or [1,0,1,1]
   I  - consecutive differences,           e.g. [-1,1]    or [-1,1,0]
    Ạ - All, 0 if any values are 0 else 1, e.g. 1         or 0

Works for either all uppercase or all lowercase.


4

Japt, 8 bytes

Uä> ä- e

Test it online!

How it works

Uä> ä- e  // Implicit: U = input string
Uä>       // Map each pair of chars X, Y in U to X > Y.
    ä-    // Map each pair of items in the result to X - Y.
          // If there are two consecutive rises or falls, the result contains a zero.
       e  // Check that every item is truthy (non-zero).
          // Implicit: output last expression

Same as my solution. Except 11x shorter. :P
mbomb007

4

C# 105 104 Bytes

bool f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t>0;}

105 bytes Solution:

bool f(char[]x){bool t=1>0,f=x[0]<x[1];for(int i=2,p=x[1];i<x.Length;)f^=t&=p<(p=x[i++])?!f:f;return t;}

Try it online

Using an array of chars saved one byte since the space can be omitted after the brackets. f(string x) vs f(char[]x)

It is 101 bytes if I can return an int 1/0 instead of bool true/false

int f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t;}

4

Haskell, 52 bytes

f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y

I suspect I could get this a chunk smaller if I managed to get rid of the "where" construct, but I'm probably stuck with zipWith.

This works by making a list of the rises (True) and falls (False), then making a list of if the ajacent entries in this list are different


This is my first attempt at one of these, so I'll go through my thought process in case I've gone horribly wrong somewhere.

Ungolfed Version (168 bytes)

isBumpy :: [Char] -> Bool
isBumpy input = and $ areBumps $ riseFall input
  where
    riseFall ax@(x:xs) = zipWith (>) xs ax
    areBumps ax@(x:xs) = zipWith (/=) xs ax

Shorten names, remove type information (100 bytes)

f x = and $ g $ h x
  where
    h ax@(x:xs) = zipWith (>) xs ax
    g ax@(x:xs) = zipWith (/=) xs ax

Move h into the main function as it is only used once (86 bytes)

f ax@(x:xs) = and $ g $ zipWith (>) xs ax
  where
    g ax@(x:xs) = zipWith (/=) xs ax

Realise that areBumps and riseFall are similar enough to abstract (73 bytes)

f x  = and $ g (/=) $ g (>) x
  where
    g h ya@(y:ys) = zipWith h ys ya

Note that (tail y) is shorter than ya@(y:ys) (70 bytes)

f x  = and $ g (/=) $ g (>) x
  where
    g h y = zipWith h (tail y) y

Tidy up; remove unneeded spaces (52 bytes)

f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y

... and I've just noticed a shorter Haskell answer that was posted before mine that does basically the same thing. I am terrible at spotting things.
Teron

You mean the one that doesn't work? ;-) You may use g h=tail>>=zipWith h and make it a global function to avoid the where keyword.
Christian Sievers

@ChristianSievers Fixed it, and I just noticed this answer which now does exactly the same thing as mine, rendering my answer better suited as a comment to this one.
BlackCap

4

Java 7, 157 153 150 125 117 bytes

int c(char[]z){for(int i=2,a,b,c;i<z.length;i++)if(((a=z[i-1])<(c=z[i])&(b=z[i-2])<a)|(a>=c&b>=a))return 0;return 1;}

Ungolfed & test cases:

Try it here.

class M{
  static int c(char[] z){
    for(int i = 2, a, b, c; i < z.length; i++){
      if(((a = z[i-1]) < (c = z[i]) & (b = z[i-2]) < a) | (a >= c & b >= a)){
        return 0; //false
      }
    }
    return 1; //true
  }

  public static void main(String[] a){
    System.out.print(c("ABA".toCharArray()) + ", ");
    System.out.print(c("ABB".toCharArray()) + ", ");
    System.out.print(c("BAB".toCharArray()) + ", ");
    System.out.print(c("BUMP".toCharArray()) + ", ");
    System.out.print(c("BALD".toCharArray()) + ", ");
    System.out.print(c("BALDY".toCharArray()) + ", ");
    System.out.print(c("UPWARD".toCharArray()) + ", ");
    System.out.print(c("EXAMINATION".toCharArray()) + ", ");
    System.out.print(c("AZBYCXDWEVFUGTHSIRJQKPLOMN".toCharArray()) + ", ");

    System.out.print(c("AAA".toCharArray()) + ", ");
    System.out.print(c("ACE".toCharArray()) + ", ");
    System.out.print(c("THE".toCharArray()) + ", ");
    System.out.print(c("BUMPY".toCharArray()) + ", ");
    System.out.print(c("BALDING".toCharArray()) + ", ");
    System.out.print(c("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()) + ", ");
  }
}

Output:

1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0

@TimmyD Hmm, so it's rise when a > b, but fall when a <= b, instead of > and <?
Kevin Cruijssen

@TimmyD Ok, it's fixed, and even saves 3 bytes. :)
Kevin Cruijssen

1
you can redefine your method to accept char[] so you dont have to transform your input string to char array. that should save a few bytes. PS: java ftw!
peech

1
Did you perhaps means to change String s --> char[]z?

1
You can return a truthy or falsey value, so make your method an int and return 1 or 0 :).. Puts you down to 117 bytes
Shaun Wild

3

PowerShell v2+, 83 bytes

param($n)($a=-join(1..($n.Length-1)|%{+($n[$_-1]-lt$n[$_])}))-eq($a-replace'00|11')

A little bit of a different approach. This loops through the input $n, each iteration seeing whether the previous character $n[$_-1] is -lessthan the current character $n[$_], then casting the result of that Boolean operator to an int with +. Those are -joined together into a string, stored into $a. We then check whether $a is -equal to $a with any substrings of 00 or 11 removed.


3

Python 2.7, 84 bytes

s=input()
b=s[0]<s[1]
o=1
for i in range(len(s)-1):o&=(s[i]<s[i+1])==b;b^=1
print o

Returns 1 for bumpy, 0 for otherwise

Learned some cool stuff with bitwise & and ^.
Starts with boolean b defining first pair as up/down, then tests and flips b for each following pair.
o flips to false if test fails and sticks.
Requires quotes around input (+4 bytes for raw_input() if that breaks some rule)

Test It


3

05AB1E, 9 bytes

SÇ¥0›¥_O_

Explanation

SÇ          # convert to list of ascii values
  ¥         # take delta's
   0›       # check if positive, giving a list of 1's and 0's
            # if they alternate, the word is bumpy
     ¥      # take delta's again, if we have any 0's in the list the word is not bumpy
      _     # logical negation, turning 0 into 1 and everything else to 0
       O    # sum, producing 0 for a bumpy word and 1 for a non-bumpy word
        _   # logical negation, inverting the previous 1 into 0 and vice versa

Try it online!


2

Python 2.7 (again, 84 83 bytes)

def a(s):x=s[1:];return[cmp(s[0],x)]+a(x) if x else []
print len(set(a(input())))>1

Or, 78 77 bytes without the print.

By the way, the above 56 byte Python 2.7 example breaks on, for example, "abbab" or any other input with repeated characters. Never mind, didn't read instructions. Revising.

Okay, down to 83. The triples one is nicer though.


Here's some tips for ya. 1. Remove some whitespace a(x)if x else[]. 2. Use a lambda instead a=lambda s:[cmp(s[0],s[1:])]+a(s[1:])if s[1:]else[] 3. Use a lambda at the end instead of printing. lambda s:len(set(a(s)))>1 4. if len(set(a(s))) isn't greater than 1, than it's already falsy, so you can take off >1
DJMcMayhem

2

CJam, 15 bytes

l2ew::<2ew::^:*

Try it online! (As a linefeed-separated test-suite.)

Explanation

l    e# Read input.
2ew  e# Get all (overlapping) pairs.
::<  e# Check whether each pair is strictly ascending (1) or not (0).
2ew  e# Get all (overlapping) pairs.
::^  e# Take the bitwise XOR of each pair, giving 1 if a rise and a fall alternate,
     e# and zero if there are two rises or two falls in succession.
:*   e# Product. Gives 1 only if the previous step yielded a list of 1s, meaning
     e# that any two consecutive rises/falls will turn this into a zero.

2

PHP, 80 bytes

$s=$argv[1];for($c=$s[0];$n=$s[++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n;

or

for($c=$argv[1][0];$n=$argv[1][++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n;

empty output for false, 1 for true

or Hedi´s recursive approach ported and a little golfed for 70 bytes:

function f($s){return!$s[2]|$s[0]<$s[1]^$s[1]<$s[2]&&f(substr($s,1));}

Actually, this should recurse infinitely for bumpy words, but it does not!


2

Haskell, 30 37 bytes

q f=tail>>=zipWith f;k=and.q(/=).q(>)

Usage:

Prelude> k <$> words "ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN"
[True,True,True,True,True,True,True,True,True]

Prelude> k <$> words "AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ"
[False,False,False,False,False,False,False]

That doesn't accept "bald", foldl1(/=) doesn't do what you think it does.
Christian Sievers

@ChristianSievers Auch, you're right. Thanks for the heads up
BlackCap

2

PHP 7, 137 118 bytes

for($i=0;$i<strlen($argv[1])-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;}

Empty output for Bumpy, 0 for Not Bumpy.

This is my first attempt at code golfing and I have to improve a lot, but it was a wonderful method to learn new things for me. I also wanted to challenge myself on that task by using the new PHP 7 Spaceship Operator which seems very interesting.

Anyway I'm not satisfied about it, first of all for the fact that I had to add an extra if(isset($s[$i+2])) to check if the variable exist because I did not find another workaround to the problem, but this is it for now. (Note: I fixed that simply by changing strlen($s)-1 to strlen($s)-2, I couldn't really see that before...).

Testing code:

$as = array("ABA", "ABB", "BAB", "BUMP", "BALD", "BALDY", "UPWARD", 
            "EXAMINATION", "AZBYCXDWEVFUGTHSIRJQKPLOMN", "AAA", "BBA", 
            "ACE", "THE", "BUMPY", "BALDING", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

foreach ($as as $s) {
    for($i=0;$i<strlen($s)-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;}
}

Test online


Hello, and welcome to PPCG! Great first post!
NoOneIsHere

Welcome to PPCG! Nice first post. Check out Tips for PHP for some additional golfing suggestions.
AdmBorkBork

1

Javascript ES6, 100 bytes

d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r}

Try it here:

d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r}
alert(a(prompt()));

Oh come on two people already beat me to it by 40 bytes... whatever


Hint: "A"<"B", so you don't need to get the chars' charcodes.
ETHproductions

Also, this returns 1 for BUMPY (or anything else that contains both a rise and a fall).
ETHproductions

This doesn't seem to quite work right.
AdmBorkBork

1

Python 3, 148 139 127 bytes

def _(w):*r,=map(lambda a,b:0>ord(a)-ord(b)and-1or 1,w,w[1:]);s=len(r)%2==0and r+[r[0]]or r;return sum(s)in(-1,1)and s==s[::-1]

testing code

positives = ('ABA', 'ABB', 'BAB', 'BUMP', 'BALD', 'BALDY', 'UPWARD', 'EXAMINATION', 'AZBYCXDWEVFUGTHSIRJQKPLOMN')
negatives = ('AAA', 'BBA', 'ACE', 'THE', 'BUMPY', 'BALDING', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

for w in positives:
    print(_(w), w)
    assert _(w)

for w in negatives:
    print(_(w), w)
    assert not _(w)

i really suck at this #facepalm
Jeffrey04

Welcome to PPCG! Check out Tips for Golfing in Python, and take inspiration from the other answers.
AdmBorkBork

1

C, 65 57 60 bytes

 r;f(char*s){for(r=0;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

is fix of

r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

that works correctly with any data only at single function call (when the global variable r is initialized to zero).

But in any case this is shorter than previous solution (65 bytes) due to use of for instead of while. But previous (the following) is a little easier to understand:

r;f(char*s){while(*++s)if(!(r=~r&1<<(*s>*(s-1))))break;return r;}

My solution is based on bitwise & with inverted previous and current direction code, where direction code can be 2 (1<<1) for character code increase (*s > *(s-1)) or 1 (1<<0) otherwise. Result of this operation became 0 if we use the same direction code as previous and current, i.e. when word is not Bumpy.

UPDATE:

Code for testing:

#include <stdio.h>
#include <string.h>

r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

int main(void)
{
    char * Truthy[] = { "ABA", 
                        "ABB", 
                        "BAB",
                        "BUMP",
                        "BALD",
                        "BALDY",
                        "UPWARD",
                        "EXAMINATION",
                        "AZBYCXDWEVFUGTHSIRJQKPLOMN" };
    char * Falsey[] = { "AAA",
                        "BBA",
                        "ACE",
                        "THE",
                        "BUMPY",
                        "BALDING",
                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    int posTestNum = sizeof(Truthy) / sizeof(char *);
    int negTestNum = sizeof(Falsey) / sizeof(char *);
    int i;
    int rate = 0;
    int tests = 0;
    int res = 0;
    printf("Truthy (%d tests):\n", posTestNum);
    for (i = 0; i < posTestNum; i++)
    {
        tests++;
        printf("%s - %s\n", Truthy[i], f(Truthy[i]) ? (rate++, "OK") : "Fail");
        r = 0;
    }
    printf("\nFalsey (%d tests):\n", negTestNum);
    for (i = 0; i < negTestNum; i++)
    {
        tests++;
        printf("%s - %s\n", Falsey[i], f(Falsey[i]) ? "Fail" : (rate++, "OK"));
        r = 0;
    }
    printf("\n%d of %d tests passed\n", rate, tests);
    return 0;
}

Per meta consensus, functions have to be reusable. That means you cannot reset r to 0 for free, but must do so from within the function.
Dennis

@Dennis You're right, initialization is required, but only for repeated calls. Let's assume that for a single call that works with any data because compiler provide initialisation for global variables
VolAnd

I think you should make the 60 byte solution your main one, since the 57 byte version isn't valid by that meta post I cited.
Dennis

@Dennis Done! +3 bytes
VolAnd

1

PHP, 100 bytes

for($s=$argv[1];$i<strlen($s)-1;$i++)$s[$i]=$s[$i+1]>$s[$i]?r:f;echo str_replace([rr,ff],'',$s)==$s;

Replaces every char of the string (except the last one obviously) with an r for rise or an f for fall and then checks whether rr or ff occur in the string. To avoid that the last remaining character interfers with that, input must be all uppercase.

I'm very unsatisfied with the loop, for example I have a feeling that there must be a way to combine the $i++ into one of the several $is used in the loop, but I failed to find that way. Maybe someone else sees it.

(That's also why I posted my code, despite it being 20 (!) bytes longer than Titus' nice solution.)


0

Java 8, 114 90 bytes

(c,b)->{b=c[0]<c[1];for(int i=2;i<c.length;i++)if(c[i]>c[i-1]!=(b=!b))return 0;return 1;};

Ungolfed test program

public static void main(String[] args) {
    BiFunction<char[], Boolean, Integer> func = (c, b) -> {
        b = c[0] < c[1];
        for (int i = 2; i < c.length; i++) {
            if (c[i] > c[i - 1] != (b = !b)) {
                return 0;
            }
        }
        return 1;
    };

    System.out.println(func.apply("ABCDEFG".toCharArray(), false));
    System.out.println(func.apply("AZBYCXDGEF".toCharArray(), false));
    System.out.println(func.apply("ZXZXZX".toCharArray(), false));
    System.out.println(func.apply("ZXCYZ".toCharArray(), false));
    System.out.println(func.apply("AAA".toCharArray(), false));
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.