现在都在一起了


24

给定数字1到9的列表,输出是否将每个数字组合在一起作为单个连续块。换句话说,相同数字中没有两个用不同数字分隔。如果完全没有数字就可以了。最少的字节数获胜。

输入:数字1到9的非空列表。它可以是十进制数字,字符串,列表或类似序列。

输出:一致的Truthy值,如果所有的位在连续的块进行分组,并且提供一致的Falsey如果它们不值。

真实情况:

3
51
44999911
123456789
222222222222222222222

错误的情况:

818
8884443334
4545
554553
1234567891


2
单例字符串列表是可接受的输入格式吗?
丹尼斯

是的,单身人士很好。
xnor

谁能告诉我解决这个问题的最有效算法是什么?还是存在一个我可以查找的更普遍的问题?

@ amt528您可以通过线性遍历每个数字并检查是否没有超出第一个数字来在线性时间内执行此操作。
xnor

您能否提供一个实施示例?

Answers:


18

Python 3、38 34 33字节

lambda s:s==sorted(s,key=s.index)

这需要一个数字列表或单例字符串作为参数。在Ideone上进行测试

感谢@xsot打高尔夫球4个字节!

感谢@immibis打高尔夫球1个字节!


如果允许您代替接受字符串列表,则可以将其缩短为lambda s:s==sorted(s,key=`s`.find)
xsot

啊,我试过列出一个清单,但我没想到要使用反引号...我会问问OP。
丹尼斯

我在想什么吗-为什么不能只使用s.find呢?
user253751 '16

@immibis s必须是单例字符串的列表(或者我必须转换s为列表以进行比较),并且list.find未定义...
Dennis

@丹尼斯s.index呢?似乎为我工作。
user253751 '16

14

JavaScript(ES6),27个字节

s=>!/(.)(?!\1).*\1/.test(s)

使用负前瞻查找两个不连续的数字。如果存在至少两个这样的数字,则可以选择它们,以便第一个数字在另一个数字之前。


1
或者,只需使用正则表达式XD。那也行。
Conor O'Brien

1
ahem视网膜ahem
John Dvorak

13

05AB1E,4个字节

码:

Ô¹ÙQ

说明:

Ô     # Push connected uniquified input. E.g. 111223345565 would give 1234565.
 ¹    # Push input again.
  Ù   # Uniquify the input. E.g. 111223345565 would give 123456.
   Q  # Check if equal, which yields 1 or 0.

使用CP-1252编码。

在线尝试!


2
你...打败果冻...我从来没有想过这是可能的...
巴林特

11

果冻,5 个字节

ĠIFPỊ

在线尝试!

怎么运行的

ĠIFPỊ  Main link. Input: n (list of digits or integer)

Ġ      Group the indices of n by their corresponding values, in ascending order.
       For 8884443334, this yields [[7, 8, 9], [4, 5, 6, 10], [1, 2, 3]].
 I     Increments; compute the all differences of consecutive numbers.
       For 8884443334, this yields [[1, 1], [1, 1, 4], [1, 1]].
  F    Flatten the resulting 2D list of increments.
   P   Product; multiply all increments.
    Ị  Insignificant; check if the product's absolute value is 1 or smaller.

你说五个字节?那是什么样的编码?
约翰·德沃夏克

4
Jelly有自己的代码页该页将它可以理解的256个字符中的每个字符编码为一个字节。
丹尼斯

9

Pyth,6个 5字节

1个字节,感谢FryAmTheEggman

SIxLQ

受到此处 Python解决方案的启发。

测试套件

说明:

SIxLQ
  xLQ   Map each element in the input to its index in the input. Input is implicit.
SI      Check whether this list is sorted.

3
SIxLQ似乎有效。
FryAmTheEggman '16

这是天才。
Maltysen '16

1
第二个Q似乎没有正确解析,它交换了参数顺序或其他东西,所以得到all 0,并且总是为true。这是一个测试套件。
FryAmTheEggman '16

8

R,66 48 46 43 38字节

function(s)!any(duplicated(rle(s)$v))

此函数接受输入作为数字向量,并返回布尔值。要调用它,请将其分配给变量。

不是最短的,但我认为这是一个有趣的方法。我们对输入进行长度编码并提取值。如果值列表包含重复项,则返回FALSE,否则返回TRUE

在线验证所有测试用例

MickyT节省了20个字节,Albert Masclans节省了3个字节,mnel节省了5个字节!


7

MATL,8字节

t!=tXSP=

输出是一个仅包含一个真值的数组,或者一个包含至少一个零的假值数组。

在线尝试!

说明

考虑22331满足条件的输入。测试每个字符是否彼此相等,即可得出2D数组

1 1 0 0 0
1 1 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 1

如果该数组的行(视为原子)按(字典顺序)降序排列,则最终结果应该是真实。为了进行比较,输入22321给出了数组

1 1 0 1 0
1 1 0 1 0
0 0 1 0 0
1 1 0 1 0
0 0 0 0 1

其中的行未排序。

t!   % Take string input. Duplicate and tranpose
=    % Test for equality, element-wise with broadcast: gives a 2D array that
     % contains 0 or 1, for all pairs of characters in the input
t    % Duplicate
XS   % Sort rows (as atomic) in increasing order
P    % Flip vertically to obtain decreasing order
=    % Test for equality, element-wise

5

视网膜,17字节

M`(.)(?!\1).+\1
0

在线尝试!(稍作修改即可一次运行所有测试用例。)

其中第一个正则表达式匹配的数字其他数字分开,这样我们就得到一个0之间的有效投入,并在任何地方19无效的输入(因的的贪婪.+,我们不能得到超过n-1的匹配n不同的数字)。

为了反转结果的真实性,我们计算0s 的数量,该数量1用于有效输入和0无效输入。


我做了一个简短的评论,但它与您的评论足够接近,应该改为评论。使用AntiGrep代替Match,然后删除最后一行:A`(.)(?!\1).+\115字节。也适用于多个输入。真实是输入,虚假是什么。一个人不会仅仅用自己的语言超越马丁。:)
mbomb007

@ mbomb007我想我实际上是认为,但不幸的是,挑战要求 一致的真实(和虚假)值,因此不允许将输入打印为真实。
Martin Ender

5

Java,161156字节

因为Java ...

无耻地窃取借用的正则表达式这个答案,因为我开始尝试与阵列和数学操作要做到这一点,但它得到了可怕复杂,正则表达式是一个很好的工具,因为任何针对此问题。

import java.util.regex.*;public class a{public static void main(String[] a){System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(a[0]).find());}}

取消高尔夫:

import java.util.regex.*;

public class a {
    public static void main(String[] args) {
        System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(args[0]).find());
    }

像一个明智的Java人一样布置:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class  {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(.)(?!\\1).*\\1");
        Matcher m = p.matcher(args[0]);
        System.out.println(!m.find());
    }
}

3
like a sensible Java person那将是,永远不会使用Java。

其他解决方案仅提供功能,会使它缩短很多。像s->s.match("(.)(?!\\1).*\\1")
Andreas

2
但是,我们无法陶醉于答案的冗长。
JamesENL '16


4

Ruby,23个字节

匿名函数。接受一个字符串。正则表达式分层。

->n{/(.)(?!\1).*\1/!~n}

正则表达式细分

/(.)(?!\1).*\1/
 (.)            # Match a character and save it to group 1
    (?!\1)      # Negative lookahead, match if next character isn't
                #  the same character from group 1
          .*    # Any number of matches
            \1  # The same sequence as group 1

!~表示如果字符串中不存在正则表达式的匹配项,则返回return true,否则返回return false



4

MATL,13 11字节

u"G@=fd2<vA

感谢Luis Mendo节省了两个字节!

在线尝试!

说明

        % Grab the input implicitly
u       % Find the unique characters
"       % For each of the unique characters
    G   % Grab the input again
    @=  % Determine which chars equal the current char
    f   % Find the locations of these characters
    d   % Compute the difference between the locations
    2<  % Find all index differences < 2 (indicating consecutive chars)
    v   % Vertically concatenate all stack contents
    A   % Ensure that they are all true
        % Implicit end of the for loop

您可以使用带引号的输入(默认情况下允许)并删除j。另外,我认为您可以vA在循环内移动并删除]
Luis Mendo

@LuisMendo谢谢!我把Y&里面弄得一团糟,但这没用,因为它fd2<可能是空的。vA虽然进入内部效果很好!我也真的希望我们有一个unique不占用大量字节的马stable 。
Suever,2016年

现在,使用数字而不是预定义的字符串可以使稳定的唯一性花费更少。不过,我将来可能会添加一个较短的版本。或仅在u默认情况下使其稳定(S此后始终可以包括两个字节)。你怎么看?
路易斯·门多

3

Haskell,44个字节

import Data.List 
((==)<*>nub).map head.group

用法示例:((==)<*>nub).map head.group $ "44999911"-> True

非无点版本:

f x = q == nub q                -- True if q equals q with duplicates removed
  where
  q = map head $ group x        -- group identical digits and take the first
                                -- e.g. "44999911" -> ["44","9999","11"] -> "491"
                                -- e.g  "3443311" -> ["3","44","33","11"] -> "3431"

3

J,8个字节

-:]/:i.~

J.js进行测试

怎么运行的

-:]/:i.~  Monadic verb. Argument: y (list of digits)

     i.~  Find the index in y of each d in y.
  ]/:     Sort y by the indices.
-:        Match; compare the reordering with the original y.

1
:] :i :-1
CalculatorFeline

11
不知道是否开玩笑或打高尔夫球的建议...
丹尼斯

3

Python,56 55字节

a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1

在Python 3.4.1中失败(int not subscriptable
CalculatorFeline

使用保存了一个额外的字节~(从字面上等价于1-):a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1
CalculatorFeline

3

C#,119个字节

bool m(String s){for(int i=0;i<9;i++){if(new Regex(i.ToString()+"+").Matches(s).Count>1){return false;}}return true;}

不打高尔夫球

bool m(String s) {
    for(int i=0;i<9;i++) {
        if(new Regex(i.ToString() + "+").Matches(s).Count > 1) {
            return false;
        }
    }

    return true;
}

1
Welcome to PPCG! Instead of deleting a post and making a new post with the fixed version, you could also edit your old post and then undelete it. (No need to do that now that there's two posts already anyway, but just so you know in the future.)
Martin Ender

My bad. When I first intended to participate in this Code Golf I misread the objective and didn't had much time to do another solution ( and knowing myself, I wouldn't try to correct the previous posted solution ). But then I was told I had some more time free and attempted to post the "correct solution". Didn't even thought in doing what you said. Next time I'll have that in mind!
auhmaan

No problem at all, I hope you'll have a good time in the community. :)
Martin Ender

2

Julia, 35 bytes

s->issorted(s,by=x->findfirst(s,x))

For whatever reason, sort does not take a string, but issorted does...


...Are strings not immutable arrays in Julia like Python? That would make me really sad.
cat

1
Yes, strings are immutable. That's probably why issorted works, but sort doesn't.
Dennis

1
There isn't a sorting method defined for strings, but it wouldn't work if they were processed in the same way as one-dimensional arrays because those are sorted by performing an in-place sort of a copy, and as you said, strings are immutable. It's not a problem for checking for sorted order though because it's implemented as a simple loop over an iterable, which is fine for strings. Just some trivia. ¯\_(ツ)_/¯
Alex A.

@AlexA. So very much like Python in fact; the difference is that Python's builtin sorted turns its iterable argument into a mutable list first -- that's why sorted(string) returns a list of strings
cat

2

Factor, 22 bytes

[ dup natural-sort = ]

Does what it says on the tin. As an anonymouse function, you should call this, or make it a : word ;.


4
it scares me when a cat brings a mouse into the game
downrep_nation

@downrep_nation :P
cat

2

Lua, 107 94 85 Bytes

13 bytes saved thanks to @LeakyNun

At least, it beats Java :D. Lua sucks at manipulating strings, but I think it is good enough :).

It takes its input as a command-line argument, and outputs 1 for truthy cases and false for falsy ones. Now outputs using its exit code. Exit code 0 for truthy, and 1 for falsy

o=os.exit;(...):gsub("(.)(.+)%1",function(a,b)if 0<#b:gsub(a,"")then o(1)end end)o(0)

Ungolfed

Be care, there's two magic-variables called ..., the first one contains the argument of the program, the second one is local to the anonymous function and contains its parameters

o=os.exit;               -- ; mandatory, else it would exit instantly
(...):gsub("(.)(.+)%1",  -- iterate over each group of the form x.*x and apply an anonymous
  function(a,b)          -- function that takes the captured group as parameters
  if 0<#b:gsub(a,"")     -- if the captured group (.+) contain other character than
  then                   -- the one captured by (.)
    o(1)                 -- exit with falsy
  end
end)
o(0)                     -- exit with truthy, reached only when the string is okay

If it is permitted, you can replace os.exit() with i=#0...
Leaky Nun

1

JavaScript ES6, 71 69 bytes

h=y=>y.match(/(.)\1*/g);x=>h((u=h(x)).sort().join``).length==u.length

Or, equivalently:

x=>((u=x.match(r=/(.)\1*/g)).sort().join``).match(r).length==u.length
x=>(h=y=>y.match(/(.)\1*/g))((u=h(x)).sort().join``).length==u.length

Golfing in progress.

Verify test cases

var truthy = `3
51
44999911
123456789
222222222222222222222`.split `
`;
var falsey = `818
8884443334
4545
554553
1234567891`.split `
`;

var Q = x => ((u = x.match(r = /(.)\1*/g)).sort().join ``).match(r).length == u.length;
truthy.concat(falsey).forEach(e => {
  t = document.createTextNode(`${e} => ${Q(e)}`);
  o.appendChild(t);
  o.appendChild(document.createElement("br"));
});
* {
  font-family: Consolas, monospace;
}
<div id=o></div>


1

C# 111 bytes

bool f(string s){for(int i=0;i<s.Length-1;i++)if(s[i]!=s[i+1]&&s.LastIndexOf(s[i])!=i)return 1==2;return true;}

old strategy 131 bytes

bool s(string i){var f=Regex.Matches(i,@"([0-9])\1{0,}").Cast<Match>().Select(m=>m.Value[0]);return f.Distinct().SequenceEqual(f);}

first golf i think i did ok in


1

C, 74 73 71 bytes

Shaved one three byte thanks to @xsot!

a[99],c,m;main(d){for(;~c;m|=c^d&&a[d=c]++)c=getchar();putchar(48+!m);}

a[99] I love Perl's autovivification! Oh, wait...
cat

I think this works: a[99],c,m;main(d){for(;~c;m|=a[d=c]+=c!=d)c=getchar();putchar(48+1/m);}
xsot

@xsot - Thank you for shaving one byte by replacing !--m with 1/m. About a[d=c]+=c!=d, I tried it with gcc and it didn't work on my computer because of order of evaluation. We must find a compiler that will play along.
mIllIbyte

Oh, I just tested it on ideone and it worked fine. How about this: a[99],c,m;main(d){for(;~c;m|=c^d&&a[d=c]++)c=getchar();putchar(48+!m);}
xsot

1

Haskell, 37 bytes

f l=(==)=<<scanl1 min$(<$>l).(==)<$>l

Uses the same approach as Luis Mendo's MATL answer: creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.

(<$>l).(==)<$>l is shorter version of [map(==a)l|a<-l]. The function (<$>l).(==) that takes a to map(==a)l is mapped onto l.

scanl1 min takes the cumulative smallest elements of l, which equals the original only if l is reverse-sorted. (==)=<< checks if the list is indeed invariant under this operation.


A different recursive strategy gave 40 bytes:

f(a:b:t)=f(b:t)>(elem a t&&a/=b)
f _=1>0

This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block.


1

Racket, 53 bytes

The dumb, simple version.

(λ(s)(let([s(string->list s)])(eq?(sort s char<?)s)))

Ungolfed:

(define (lame-all-together s)
  (let ([s (string->list s)])
    (eq? (sort s char<?) s)))

Racket, 86 bytes

Here's the version implementing @xnor's comment about more efficient ways to do this.

(λ(s)(let([s(string->list(regexp-replace#px"(.)\\1+"s"\\1"))])(eq?(sort s char<?)s)))

Ungolfed:

(define (all-together s)
    (let ([s (string->list (regexp-replace #px"(.)\\1+" s "\\1"))])
      (eq? (sort s char<?) s )))

Okay, this may actually just shift the weight of computation from the sort function to regexp-replace, but it was an interesting solution. Basically, it removes runs of duplicate characters first (see here), then tests if the remaining length-1 runs are in sorted fashion.


1

Perl 5, 20 bytes

19, plus 1 for -pe instead of -e.

$_=!/(.)(?!\1).+\1/

1

Wolfram Language (Mathematica), 18 bytes

Gather@#==Split@#&

Try it online!

Gather gathers a list into sublists of identical elements, and Split splits a list into sublists of consecutive identical elements. They give the same result if and only if each value appears in only one contiguous block.



0

Japt, 9 bytes

ò¦ mÌ
eUâ

Try it


Explanation

          :Implicit input of string U             :e.g., "8884443334"
ò¦        :Split on inequality                    :["888","444","333","4"]
   mÌ     :Map and return the last digit of each  :["8","4","3","4"]
\n        :Assign to U
  Uâ      :Remove duplicates                      :["8","4","3"]
e         :Test for equality with U               :false
          :Implicit output of result

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.