2
$\begingroup$

I have a text file containing a list of numbers. I want to print only the lines that contain a number, the digits of which are consecutive digits.

The input list:

123
321
567
765
124
568

The output should be:

123
321
567
765

$\endgroup$
1
  • $\begingroup$ Pick and Cases could do the job? $\endgroup$
    – Teabelly
    Commented Oct 24, 2018 at 17:33

3 Answers 3

3
$\begingroup$
consecutive = Total[Abs[Differences[IntegerDigits@FromDigits@#]] - 1] &;
string = "123 321 567 765 124 568";
Pick[#,  consecutive /@ #, 0]& @ StringSplit[string]

{"123", "321", "567", "765"}

$\endgroup$
1
  • $\begingroup$ Thank you @AccidentalFourierTransform. $\endgroup$
    – kglr
    Commented Oct 24, 2018 at 19:22
1
$\begingroup$
string = "5 1234 56 58 123 321 567 765 124 568";

Cases[
 ToExpression @ Characters @ StringSplit[string],
 a : {__} /; Union @ Abs @ Differences @ a == {1} :> StringRiffle[a, ""]]

{"1234", "56", "123", "321", "567", "765"}

$\endgroup$
1
$\begingroup$
string = "123 321 567 765 124 568";

Using StringSplit and Select:

sp = StringSplit[string, " "];

consecutive = Abs[Times @@Differences[IntegerDigits[ToExpression@#]]] == 1 &;

Select[sp, consecutive@# &]

{"123", "321", "567", "765"}

Or using StringSplit and DeleteCases:

DeleteCases[sp, s_ /; ! consecutive[s]]

{"123", "321", "567", "765"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.