すべて一緒に今


24

1から9までの数字のリストが与えられると、各数字が単一の連続したブロックとしてグループ化されるかどうかを出力します。つまり、同じ数字の2つが異なる数字で区切られていません。数字がまったく表示されなくても問題ありません。少ないバイトが勝ちます。

入力: 1から9までの数字の空でないリスト。これは、10進数、文字列、リスト、または同様のシーケンスにすることができます。

出力:一貫したTruthyの値のすべての桁が連続したブロックにグループ化されている場合、および一貫性のFalseyの値はそうではありません場合。

真の場合:

3
51
44999911
123456789
222222222222222222222

偽の場合:

818
8884443334
4545
554553
1234567891


2
シングルトン文字列のリストは受け入れ可能な入力形式でしょうか?
デニス

はい、シングルトンでも構いません。
-xnor

この問題の最も効率的なアルゴリズムは何でしょうか?それとも、これが当てはまるというより一般的な問題がありますか?

@ amt528各桁を反復処理し、最初の桁を超えて実行されていないことを確認することで、線形時間で実行できます。
-xnor

実装方法の例を教えてください。

回答:


18

Pythonの3、38の 34 33バイト

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

これには、引数として数字またはシングルトン文字列のリストが必要です。Ideoneでテストします。

4バイトのゴルフを楽しんでくれた@xsotに感謝します!

1バイトのゴルフをしてくれた@immibisに感謝します!


代わりに文字列のリストを受け入れることが許可されている場合、これを短縮することができますlambda s:s==sorted(s,key=`s`.find)
-xsot

ああ、私はリストを取得しようとしましたが、バッククォートの使用を考えていませんでした...私はOPに尋ねます。
デニス

私は何かが欠けていますか-なぜあなたはちょうど使用できないのですs.findか?
user253751

@immibis sはシングルトン文字列のリストである必要があり(またはs、比較のためにリストにキャストする必要があります)、list.find定義されていません...-
デニス

@デニスs.index?私のために働くようです。
user253751

14

JavaScript(ES6)、27バイト

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

負の先読みを使用して、2つの連続していない数字を探します。そのような数字が少なくとも2つ存在する場合は、最初の数字が別の数字の前にくるように選択できます。


1
または、正規表現XDを使用します。それも機能します。
コナーオブライエン

1
エヘン網膜エヘン
ジョンドヴォルザーク

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.

あなたが言う5バイト?それはどのようなエンコーディングですか?
ジョンドヴォルザーク

4
Jellyには、独自のコードページがあり、256バイトの各文字を1バイトとして認識します。
デニス

9

Pyth、6 5バイト

FryAmTheEggmanのおかげで1バイト

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

これは天才です。
マルティセン

1
2番目Qは適切に解析されないようです。引数の順序などを入れ替えるため、すべて0のs を取得し、常にtrueを返します。ここだテストスイートは。
FryAmTheEggman

8

R、66 48 46 43 38バイト

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

これは、入力を数字のベクトルとして受け入れ、ブール値を返す関数です。呼び出すには、変数に割り当てます。

最短ではありませんが、楽しいアプローチだと思いました。入力を長さエンコードし、値を抽出します。値のリストに重複が含まれている場合はreturn FALSE、そうでない場合はreturnTRUE

すべてのテストケースをオンラインで検証する

MickyTのおかげで20バイト、Albert Masclansのおかげで3バイト、mnelのおかげで5バイト節約されました!


7

MATL、8バイト

t!=tXSP=

出力は、真の場合は1のみを含む配列、偽の場合は少なくとも1つのゼロを含む配列です。

オンラインでお試しください!

説明

22331条件を満たすinputを考えます。各文字が互いに等しいかどうかをテストすると、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の間のどこか有効な入力用と1し、9(無効な入力のために起因するの貪欲に.+、我々はより多く得ることができないn-1ためマッチn異なる数字)。

結果の真実性を反転させるために、有効な入力と無効な入力0のs の数をカウントします。10


私は短いものを作成しましたが、あなたのものに十分近いので、代わりにコメントにする必要があります。Matchの代わりにAntiGrepを使用し、最後の行を削除しA`(.)(?!\1).+\1ます:15バイト。複数の入力でも機能します。真実は入力であり、偽りは何もない。単に自分の言語でゴルフマーティンを追い抜くことはありません。:)
mbomb007

@ mbomb007私は実際に考えたと思いますが、残念ながら、チャレンジは一貫した真実の(そして偽の)値を要求するため、入力を真実として出力することは許可されていません。
マーティンエンダー

5

Java、161 156バイト

なぜなら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")
アンドレアス

2
しかし、その場合、答えの詳細さを楽しむことができませんでした。
JamesENL


4

ルビー、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

2バイトを節約してくれた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ループ内を移動して削除できると思います]
ルイスメンドー

@LuisMendoありがとう!私はY&中に入れることをいじりましたが、それはfd2<空であることができるのでうまくいきませんでした。vA内側に移動するのは素晴らしいことです!またunique、多くのバイトを必要としない安定版があればいいのにと思います。
-Suever

事前定義された文字列の代わりに数字を使用して、stable uniqueの所要時間が少し少なくなりました。ただし、将来はもっと短いバージョンを追加するかもしれません。またはu、デフォルトで安定させるだけです(Sその後は常に2バイトを含めることができます)。どう思いますか?
ルイスメンドー

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
Not sure if joke or golfing suggestion...
Dennis

3

Python, 56 55 bytes

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

Fails in Python 3.4.1 (int not subscriptable)
CalculatorFeline

Saved an extra byte with ~(which literally is equivalent to1-): a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1
CalculatorFeline

3

C#, 119 bytes

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

Ungolfed

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/



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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.