Rep-string: Difference between revisions

27,089 bytes added ,  2 months ago
m
→‎{{header|ABC}}: Added main program
(Add BCPL)
m (→‎{{header|ABC}}: Added main program)
 
(31 intermediate revisions by 18 users not shown)
Line 35:
{{trans|Python: Functional}}
 
<langsyntaxhighlight lang="11l">F reps(text)
R (1 .< 1 + text.len I/ 2).filter(x -> @text.starts_with(@text[x..])).map(x -> @text[0 .< x])
 
V matchstr =
|‘1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1’
 
L(line) matchstr.split("\n")
print(‘'#.' has reps #.’.format(line, reps(line)))</langsyntaxhighlight>
 
{{out}}
Line 67:
'00' has reps [0]
'1' has reps []
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN repstrings str:
PUT {} IN reps
FOR len IN {0..floor(#str/2-1)}:
PUT str|floor(#str/2-len) IN rep
PUT rep IN rpt
WHILE #rpt < #str: PUT rpt^rep IN rpt
IF rpt|#str = str: INSERT rep IN reps
RETURN reps
 
PUT {} IN tests
PUT "1001110011" IN tests[1]
PUT "1110111011" IN tests[2]
PUT "0010010010" IN tests[3]
PUT "1010101010" IN tests[4]
PUT "1111111111" IN tests[5]
PUT "0100101101" IN tests[6]
PUT "0100100" IN tests[7]
PUT "101" IN tests[8]
PUT "11" IN tests[9]
PUT "00" IN tests[10]
PUT "1" IN tests[11]
 
FOR t IN tests:
WRITE t, repstrings t /
</syntaxhighlight>
{{out}}
<pre>1001110011: {"10011"}
1110111011: {"1110"}
0010010010: {"001"}
1010101010: {"10"; "1010"}
1111111111: {"1"; "11"; "111"; "1111"; "11111"}
0100101101: {}
0100100: {"010"}
101: {}
11: {"1"}
00: {"0"}
1: {}</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC IsCycle(CHAR ARRAY s,sub)
BYTE i,j,count
 
IF sub(0)=0 OR s(0)<sub(0) THEN
RETURN (0)
FI
 
j=1 count=0
FOR i=1 TO s(0)
DO
IF s(i)#sub(j) THEN
RETURN (0)
FI
j==+1
IF j>sub(0) THEN
j=1 count==+1
FI
OD
IF count>1 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Test(CHAR ARRAY s)
CHAR ARRAY sub
BYTE len,count
 
PrintF("%S -> ",s)
count=0
FOR len=1 TO s(0)-1
DO
SCopyS(sub,s,1,len)
IF IsCycle(s,sub) THEN
IF count>0 THEN
Print(", ")
FI
Print(sub)
count==+1
FI
OD
IF count=0 THEN
Print("none")
FI
PutE()
RETURN
 
PROC Main()
Test("1001110011")
Test("1110111011")
Test("0010010010")
Test("1010101010")
Test("1111111111")
Test("0100101101")
Test("0100100")
Test("101")
Test("11")
Test("00")
Test("1")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Rep-string.png Screenshot from Atari 8-bit computer]
<pre>
1001110011 -> 10011
1110111011 -> 1110
0010010010 -> 001
1010101010 -> 10, 1010
1111111111 -> 1, 11, 111, 1111, 11111
0100101101 -> none
0100100 -> 010
101 -> none
11 -> 1
00 -> 0
1 -> none
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed;
 
procedure Rep_String is
Line 101 ⟶ 216:
Ada.Text_IO.Put_Line("Longest rep-string for """& X &""": """& Y &"""");
end if;
end Rep_String;</langsyntaxhighlight>
 
{{out}}
Line 130 ⟶ 245:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># procedure to find the longest rep-string in a given string #
# the input string is not validated to contain only "0" and "1" characters #
PROC longest rep string = ( STRING input )STRING:
Line 197 ⟶ 312:
)
OD
)</langsyntaxhighlight>
{{out}}
<pre>1001110011: longest rep string: "10011"
Line 215 ⟶ 330:
This function returns a list of all possible repeated substrings.
It returns the empty list if there are none.
<langsyntaxhighlight APLlang="apl">rep ← ⊢ (⊢(/⍨)(⊂⊣)≡¨(≢⊣)⍴¨⊢) ⍳∘(⌊0.5×≢)↑¨⊂</langsyntaxhighlight>
{{out}}
<pre> rep '1001110011'
Line 243 ⟶ 358:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">------------------------REP-CYCLES-------------------------
 
-- repCycles :: String -> [String]
Line 464 ⟶ 579:
on unlines(xs)
|λ|(xs) of intercalate(linefeed)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>Longest cycle:
Line 482 ⟶ 597:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">repeated?: function [text][
loop ((size text)/2)..0 'x [
if prefix? text slice text x (size text)-1 [
Line 512 ⟶ 627:
else ->
print [str "->" rep "( length:" size rep ")"]
]</langsyntaxhighlight>
 
{{out}}
Line 530 ⟶ 645:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">In := ["1001110011", "1110111011", "0010010010", "1010101010"
, "1111111111", "0100101101", "0100100", "101", "11", "00", "1"]
for k, v in In
Line 548 ⟶ 663:
}
return "N/A"
}</langsyntaxhighlight>
{{Out}}
<pre>10011 1001110011
Line 563 ⟶ 678:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">all$ = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1"
 
FOR word$ IN all$
Line 579 ⟶ 694:
 
PRINT "Not a repeating string: ", word$
NEXT</langsyntaxhighlight>
{{out}}
<pre>
Line 594 ⟶ 709:
Not a repeating string: 1
</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT I: DEFSTR S,T
20 READ S: IF S="" THEN END
30 IF LEN(S)<2 THEN 80 ELSE FOR I = LEN(S)\2 TO 1 STEP -1
40 T = ""
50 IF LEN(T)<LEN(S) THEN T=T+LEFT$(S,I): GOTO 50
60 IF LEFT$(T,LEN(S))=S THEN PRINT S;": ";LEFT$(S,I): GOTO 20
70 NEXT I
80 PRINT S;": none"
90 GOTO 20
100 DATA "1001110011","1110111011"
110 DATA "0010010010","1010101010"
120 DATA "1111111111","0100101101"
130 DATA "0100100","101"
140 DATA "11","00"
150 DATA "1",""</syntaxhighlight>
{{out}}
<pre>1001110011: 10011
1110111011: 1110
0010010010: 001
1010101010: 1010
1111111111: 11111
0100101101: none
0100100: 010
101: none
11: 1
00: 0
1: none</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Returns the length of the longest rep-string
Line 645 ⟶ 789:
rep("00")
rep("1")
$)</langsyntaxhighlight>
{{out}}
<pre>1001110011: 10011
Line 660 ⟶ 804:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( rep-string
= reps L x y
. ( reps
Line 695 ⟶ 839:
& rep-string$00
& rep-string$1
);</langsyntaxhighlight>
{{Out}}
<pre>1001110011 : 10011
Line 708 ⟶ 852:
00 : 0
1 is not a rep-string</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn"># Returns a list of all rep-strings
Reps←(⌊≠÷2˙)((⊣≥≠¨∘⊢)/⊢)(<≡¨≠⥊¨1↓↑)/1↓↑
 
# Tests
tests←⟨
"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101",
"0100100", "101", "11", "00", "1"
 
∾´{ 𝕩∾':'∾(•Fmt Reps 𝕩)∾@+10 }¨tests</syntaxhighlight>
{{out}}
<pre>"1001110011:⟨ ""10011"" ⟩
1110111011:⟨ ""1110"" ⟩
0010010010:⟨ ""001"" ⟩
1010101010:⟨ ""10"" ""1010"" ⟩
1111111111:⟨ ""1"" ""11"" ""111"" ""1111"" ""11111"" ⟩
0100101101:⟨⟩
0100100:⟨ ""010"" ⟩
101:⟨⟩
11:⟨ ""1"" ⟩
00:⟨ ""0"" ⟩
1:⟨⟩
"</pre>
 
=={{header|C}}==
===Longest substring ===
 
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <string.h>
Line 747 ⟶ 917:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 762 ⟶ 932:
</pre>
===shortest substring===
<syntaxhighlight lang="c">
<lang c>
// strstr : Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
// size_t is an unsigned integer typ
Line 781 ⟶ 951:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
 
public class RepString
{
static readonly string[] input = {"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11",
"00", "1", "0100101"};
 
public static void Main(string[] args)
{
foreach (string s in input)
Console.WriteLine($"{s} : {repString(s)}");
}
 
static string repString(string s)
{
int len = s.Length;
for (int part = len / 2; part > 0; part--)
{
int tail = len % part;
if (tail > 0 && !s.Substring(0, tail).Equals(s.Substring(len - tail)))
continue;
bool isRepeated = true;
for (int j = 0; j < len / part - 1; j++)
{
int a = j * part;
int b = (j + 1) * part;
int c = (j + 2) * part;
if (!s.Substring(a, part).Equals(s.Substring(b, part)))
{
isRepeated = false;
break;
}
}
if (isRepeated)
return s.Substring(0, part);
}
return "none";
}
}
</syntaxhighlight>
{{out}}
<pre>
1001110011 : 10011
1110111011 : 1110
0010010010 : 001
1010101010 : 1010
1111111111 : 11111
0100101101 : none
0100100 : 010
101 : none
11 : 1
00 : 0
1 : none
0100101 : none
 
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <vector>
#include <boost/regex.hpp>
Line 819 ⟶ 1,050:
}
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>1001110011 is a rep string! Here is a repeating string:
Line 840 ⟶ 1,071:
0
1 is no rep string!</pre>
 
===Without external libraries===
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
 
std::string repeat(const std::string& text, const int32_t& repetitions) {
std::stringstream stream;
std::fill_n(std::ostream_iterator<std::string>(stream), repetitions, text);
return stream.str();
}
 
std::vector<std::string> rep_string(const std::string& text) {
std::vector<std::string> repetitions;
 
for ( uint64_t len = 1; len <= text.length() / 2; ++len ) {
std::string possible = text.substr(0, len);
uint64_t quotient = text.length() / len;
uint64_t remainder = text.length() % len;
std::string candidate = repeat(possible, quotient) + possible.substr(0, remainder);
if ( candidate == text ) {
repetitions.emplace_back(possible);
}
}
return repetitions;
}
 
int main() {
const std::vector<std::string> tests = { "1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" };
 
std::cout << "The longest rep-strings are:" << std::endl;
for ( const std::string& test : tests ) {
std::vector<std::string> repeats = rep_string(test);
std::string result = repeats.empty() ? "Not a rep-string" : repeats.back();
std::cout << std::setw(10) << test << " -> " << result << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
The longest rep-strings are:
1001110011 -> 10011
1110111011 -> 1110
0010010010 -> 001
1010101010 -> 1010
1111111111 -> 11111
0100101101 -> Not a rep-string
0100100 -> 010
101 -> Not a rep-string
11 -> 1
00 -> 0
1 -> Not a rep-string
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn rep-string [s]
(let [len (count s)
first-half (subs s 0 (/ len 2))
test-group (take-while seq (iterate butlast first-half))
test-reptd (map (comp #(take len (cycle %) cycle) test-group)]
(some #(= (seq s) %) test-reptd)))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="lisp">
(def test-strings ["1001110011"
"1110111011"
Line 863 ⟶ 1,153:
 
(map (juxt identity rep-string) test-strings)
</syntaxhighlight>
</lang>
<pre>
(["1001110011" true]
Line 877 ⟶ 1,167:
["1" nil])
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">rep_strings = iter (s: string) yields (string)
for len: int in int$from_to_by(string$size(s)/2, 1, -1) do
repstr: string := string$substr(s, 1, len)
attempt: string := ""
while string$size(attempt) < string$size(s) do
attempt := attempt || repstr
end
if s = string$substr(attempt, 1, string$size(s)) then
yield(repstr)
end
end
end rep_strings
 
start_up = proc ()
as = array[string]
po: stream := stream$primary_output()
tests: as := as$["1001110011","1110111011","0010010010","1010101010",
"1111111111","0100101101","0100100","101","11","00",
"1"]
for test: string in as$elements(tests) do
stream$puts(po, test || ": ")
for rep_str: string in rep_strings(test) do
stream$puts(po, "<" || rep_str || "> ")
end
stream$putc(po, '\n')
end
end start_up</syntaxhighlight>
{{out}}
<pre>1001110011: <10011>
1110111011: <1110>
0010010010: <001>
1010101010: <1010> <10>
1111111111: <11111> <1111> <111> <11> <1>
0100101101:
0100100: <010>
101:
11: <1>
00: <0>
1:</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(ql:quickload :alexandria)
(defun rep-stringv (a-str &optional (max-rotation (floor (/ (length a-str) 2))))
Line 898 ⟶ 1,230:
;; Recurse function reducing length of rotation.
(t (rep-stringv a-str (1- max-rotation)))))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
(setf test-strings '("1001110011"
"1110111011"
Line 916 ⟶ 1,248:
(loop for item in test-strings
collecting (cons item (rep-stringv item)))
</syntaxhighlight>
</lang>
<pre>
(("1001110011" . "10011") ("1110111011" . "1110") ("0010010010" . "001")
Line 927 ⟶ 1,259:
=={{header|Crystal}}==
{{trans|Go}}
<langsyntaxhighlight lang="ruby">def rep(s : String) : Int32
x = s.size // 2
 
Line 958 ⟶ 1,290:
 
main
</syntaxhighlight>
</lang>
 
{{out}}
Line 977 ⟶ 1,309:
=={{header|D}}==
Two different algorithms. The second is from the Raku entry.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.range, std.algorithm,
std.ascii, std.typecons;
 
Line 1,020 ⟶ 1,352:
writefln("%(%s %)", w.chunks(r1));
}
}</langsyntaxhighlight>
{{out}}
<pre>10011 10011
Line 1,037 ⟶ 1,369:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Rep_string;
 
Line 1,083 ⟶ 1,415:
end;
{$IFNDEF UNIX}readln;{$ENDIF}
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
{{trans|Go}}
<syntaxhighlight lang="dyalect">func rep(s) {
 
var x = s.Length() / 2
<lang dyalect>func rep(s) {
var x = s.len() / 2
while x > 0 {
if s.startsWithStartsWith(s.subSubstring(x)) {
return x
}
Line 1,116 ⟶ 1,446:
for s in m {
if (rep(s) is n) && n > 0 {
print("\(s) \(n) rep-string \(s.subSubstring(n))")
} else {
print("\(s) not a rep-string")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,135 ⟶ 1,465:
00 1 rep-string 0
1 not a rep-string</pre>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
func$ repstr s$ .
sl = len s$ div 2 + 1
while sl > 1
r$ = substr s$ sl 999
if r$ = substr s$ 1 len r$
return substr r$ 1 (sl - 1)
.
sl -= 1
.
return ""
.
repeat
s$ = input
until s$ = ""
print s$ & " -> " & repstr s$
.
input_data
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'list) ;; list-rotate
 
Line 1,156 ⟶ 1,519:
'too-short-no-rep))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define strings '["1001110011" "1110111011" "0010010010" "1010101010"
"1111111111" "0100101101" "0100100" "101" "11" "00" "1"])
Line 1,179 ⟶ 1,542:
"00" "0"
"1" too-short-no-rep
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Rep_string do
def find(""), do: IO.puts "String was empty (no repetition)"
def find(str) do
Line 1,210 ⟶ 1,573:
1)
 
Enum.each(strs, fn str -> Rep_string.find(str) end)</langsyntaxhighlight>
 
{{out}}
Line 1,256 ⟶ 1,619:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">REPCYCLES
=LAMBDA(s,
LET(
Line 1,292 ⟶ 1,655:
)
)
)</langsyntaxhighlight>
 
And also assuming the following generic bindings in the Name Manager:
 
<langsyntaxhighlight lang="lisp">FILTERP
=LAMBDA(p,
LAMBDA(xs,
Line 1,335 ⟶ 1,698:
NA()
)
)</langsyntaxhighlight>
 
{{Out}}
Line 1,397 ⟶ 1,760:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let isPrefix p (s : string) = s.StartsWith(p)
let getPrefix n (s : string) = s.Substring(0,n)
 
Line 1,431 ⟶ 1,794:
match repPrefixOf s with | None -> s + ": NO" | Some(p) -> s + ": YES ("+ p + ")")
|> List.iter (printfn "%s")
0</langsyntaxhighlight>
{{out}}
<pre>Testing for rep-string (and showing the longest repeated prefix in case):
Line 1,447 ⟶ 1,810:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting grouping kernel math math.ranges qw sequences ;
IN: rosetta-code.rep-string
Line 1,461 ⟶ 1,824:
0100101101 0100100 101 11 00 1 }
"Shortest cycle:\n\n" printf
[ dup find-rep-string "%-10s -> %s\n" printf ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,482 ⟶ 1,845:
{{trans|Python}}
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">: rep-string ( caddr1 u1 -- caddr2 u2 ) \ u2=0: not a rep-string
2dup dup >r r@ 2/ /string
begin 2over 2over string-prefix? 0= over r@ < and while -1 /string repeat
Line 1,502 ⟶ 1,865:
s" 11" test
s" 00" test
s" 1" test ;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="forth">cr tests
1001110011 has 10011 as repeating substring
1110111011 has 1110 as repeating substring
Line 1,516 ⟶ 1,879:
00 has 0 as repeating substring
1 has no repeating substring
ok</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<syntaxhighlight lang="freebasic">
Data "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", ""
 
Function rep(c As String, n As Integer) As String
Dim As String r
For i As Integer = 1 To n
r = r + c
Next i
Return r
End Function
 
Do
Dim As String p, b = "", t, s
Read p : If p = "" Then Exit Do
Dim As Integer l = Len(p), m = Int(l / 2)
For i As Integer = m To 1 Step -1
t = Left(p, i)
s = rep(t, l / i + 1)
If p = Left(s, l) Then b = t : Exit For
Next i
If b = "" Then
Print p; " no es una cadena repetida"
Else
Print p; " secuencia m s larga: "; b
End If
Loop
Sleep
</syntaxhighlight>
{{out}}
<pre>
1001110011 secuencia más larga: 10011
1110111011 secuencia más larga: 1110
0010010010 secuencia más larga: 001
1010101010 secuencia más larga: 1010
1111111111 secuencia más larga: 11111
0100101101 no es una cadena repetida
0100100 secuencia más larga: 010
101 no es una cadena repetida
11 secuencia más larga: 1
00 secuencia más larga: 0
1 no es una cadena repetida
</pre>
 
 
=={{header|Go}}==
{{trans|Python}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,557 ⟶ 1,970:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,574 ⟶ 1,987:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (inits, maximumBy)
import Data.Maybe (fromMaybe)
 
Line 1,629 ⟶ 2,042:
processIO xs = do
putStr (xs <> ": ")
putStrLn $ process xs</langsyntaxhighlight>
{{Out}}
<pre>1001110011: 10011
Line 1,644 ⟶ 2,057:
 
Or, alternatively:
<langsyntaxhighlight lang="haskell">import Data.Bool (bool)
import Data.List (inits, intercalate, transpose)
 
Line 1,696 ⟶ 2,109:
<*> ((" -> " <>) . fxShow . f)
)
xs</langsyntaxhighlight>
{{Out}}
<pre>Longest cycles:
Line 1,716 ⟶ 2,129:
The following works in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
every write(s := !A,": ",(repString(s) | "Not a rep string!")\1)
end
Line 1,729 ⟶ 2,142:
while *s1 < n do s1 ||:= s2
return s1[1+:n]
end</langsyntaxhighlight>
 
{{Out}}
Line 1,749 ⟶ 2,162:
Here's a test:
 
<langsyntaxhighlight lang="j">replengths=: >:@i.@<.@-:@#
rep=: $@] $ $
 
isRepStr=: +./@((] -: rep)"0 1~ replengths)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> isRepStr '1001110011'
1
Tests=: noun define
Line 1,772 ⟶ 2,185:
)
isRepStr;._2 Tests NB. run all tests
1 1 1 1 1 0 1 0 1 1 0</langsyntaxhighlight>
 
We could also report the lengths of the repeated prefix, though this seems more arbitrary:
 
<langsyntaxhighlight lang="j">nRepStr=: 0 -.~ (([ * ] -: rep)"0 1~ replengths)</langsyntaxhighlight>
 
With the above examples:
 
<langsyntaxhighlight lang="j"> ":@nRepStr;._2 Tests
5
4
Line 1,790 ⟶ 2,203:
1
1</langsyntaxhighlight>
 
Here, the "non-str-rep" cases are indicated by an empty list of prefix lengths.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class RepString {
 
static final String[] input = {"1001110011", "1110111011", "0010010010",
Line 1,824 ⟶ 2,237:
return "none";
}
}</langsyntaxhighlight>
 
{{Out}}
Line 1,839 ⟶ 2,252:
1 : none
0100101 : none</pre>
 
Alternative version avoiding the use of 'goto'
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
 
public final class RepStrings {
 
public static void main(String[] aArgs) {
List<String> tests = List.of( "1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" );
 
System.out.println("The longest rep-strings are:");
for ( String test : tests ) {
List<String> repeats = repString(test);
String result = repeats.isEmpty() ? "Not a rep-string" : repeats.get(repeats.size() - 1);
System.out.println(String.format("%10s%s%s", test, " -> ", result));
}
}
private static List<String> repString(String aText) {
List<String> repetitions = new ArrayList<String>();
for ( int length = 1; length <= aText.length() / 2; length++ ) {
String possible = aText.substring(0, length);
int quotient = aText.length() / length;
int remainder = aText.length() % length;
String candidate = possible.repeat(quotient) + possible.substring(0, remainder);
if ( candidate.equals(aText) ) {
repetitions.add(possible);
}
}
return repetitions;
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
The longest rep-strings are:
1001110011 -> 10011
1110111011 -> 1110
0010010010 -> 001
1010101010 -> 1010
1111111111 -> 11111
0100101101 -> Not a rep-string
0100100 -> 010
101 -> Not a rep-string
11 -> 1
00 -> 0
1 -> Not a rep-string
</pre>
 
=={{header|JavaScript}}==
===ES6===
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,986 ⟶ 2,451:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Longest cycles:
Line 2,004 ⟶ 2,469:
=={{header|jq}}==
For each test string, a JSON object giving details about the prefixes that satisfy the requirement is presented; if the string is not a rep-string, the empty array ([]) is shown.
<langsyntaxhighlight lang="jq">def is_rep_string:
# if self is a rep-string then return [n, prefix]
# where n is the number of full occurrences of prefix
Line 2,024 ⟶ 2,489:
| select( .[0] > 1 ) ]
;
</syntaxhighlight>
</lang>
'''Example''':
<langsyntaxhighlight lang="jq">def test:
(
"1001110011",
Line 2,042 ⟶ 2,507:
;
 
test</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh"> $ jq -n -c -f rep-string.jq
{"1001110011":[[2,"10011"]]}
{"1110111011":[[2,"1110"]]}
Line 2,055 ⟶ 2,520:
{"11":[[2,"1"]]}
{"00":[[2,"0"]]}
{"1":[]}</langsyntaxhighlight>
 
=={{header|Julia}}==
<tt>repstring</tt> returns a list of all of the substrings of its input that are the repeating units of a rep-string. If the input is not a valid rep-string, it returns an empty list. Julia indexes strings, including those that contain multi-byte characters, at the byte level. Because of this characteristic, <tt>repstring</tt> indexes its input using the <tt>chr2ind</tt> built-in.
 
<langsyntaxhighlight lang="julia">function repstring(r::AbstractString)
n = length(r)
replst = String[]
Line 2,082 ⟶ 2,547:
println("$r is a rep-string of ", join(replst, ", "), ".")
end
end</langsyntaxhighlight>
 
{{out}}
Line 2,099 ⟶ 2,564:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun repString(s: String): MutableList<String> {
Line 2,135 ⟶ 2,600:
println("${s.padStart(10)} -> ${if (size > 0) reps[size - 1] else "Not a rep-string"}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,158 ⟶ 2,623:
The heavy lifting:
 
<langsyntaxhighlight lang="lisp">
(defun get-reps (text)
(lists:filtermap
Line 2,172 ⟶ 2,637:
(1 head)
(_ '()))))
</syntaxhighlight>
</lang>
 
Displaying the results:
 
<langsyntaxhighlight lang="lisp">
(defun report
((`#(,text ()))
Line 2,187 ⟶ 2,652:
(lists:zip data (lists:map #'get-reps/1 data)))
'ok))
</syntaxhighlight>
</lang>
 
Running the code:
Line 2,220 ⟶ 2,685:
=={{header|Maple}}==
The built-in <code>Period</code> command in the <code>StringTools</code> package computes the length of the longest repeated prefix.
<langsyntaxhighlight Maplelang="maple">repstr? := proc( s :: string )
local per := StringTools:-Period( s );
if 2 * per <= length( s ) then
Line 2,227 ⟶ 2,692:
false, ""
end if
end proc:</langsyntaxhighlight>
For the given set of test strings, we can generate the following output.
<syntaxhighlight lang="maple">
<lang Maple>
> Test := ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111", \
"0100101101", "0100100", "101", "11", "00", "1"]:
Line 2,247 ⟶ 2,712:
1 false
 
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica is based on pattern-based matching, so this is very easily implemented:
<langsyntaxhighlight Mathematicalang="mathematica">RepStringQ[strin_String]:=StringCases[strin,StartOfString~~Repeated[x__,{2,\[Infinity]}]~~y___~~EndOfString/;StringMatchQ[x,StartOfString~~y~~___]:>x, Overlaps -> All]</langsyntaxhighlight>
Trying it out for the test-strings:
<syntaxhighlight lang="text">str={"1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"};
{#,RepStringQ[#]}&/@str//Grid</langsyntaxhighlight>
{{out}}
<pre>1001110011 {10011}
Line 2,269 ⟶ 2,734:
It outputs all the possibilities for a rep-string,
if there is no rep-string it will show an empty list {}.
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map test tests))]
 
test :: [char]->[char]
test s = s ++ ": " ++ show (repstrings s)
 
tests :: [[char]]
tests = ["1001110011", "1110111011", "0010010010", "1010101010",
"1111111111", "0100101101", "0100100", "101", "11", "00",
"1"]
 
repstrings :: [*]->[[*]]
repstrings s = filter matching bases
where bases = [take n s | n<-[1..#s div 2]]
matching r = s = take (#s) (concat (repeat r))</syntaxhighlight>
{{out}}
<pre>1001110011: ["10011"]
1110111011: ["1110"]
0010010010: ["001"]
1010101010: ["10","1010"]
1111111111: ["1","11","111","1111","11111"]
0100101101: []
0100100: ["010"]
101: []
11: ["1"]
00: ["0"]
1: []</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE RepStrings;
FROM InOut IMPORT Write, WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Copy, Length;
 
(* Find the length of the longest rep-string given a string.
If there is no rep-string, the result is 0. *)
PROCEDURE repLength(s: ARRAY OF CHAR): CARDINAL;
VAR strlen, replen, i, j: CARDINAL;
ok: BOOLEAN;
BEGIN
strlen := Length(s);
FOR replen := strlen DIV 2 TO 1 BY -1 DO
ok := TRUE;
i := 0;
WHILE ok AND (i < replen) DO
j := i + replen;
WHILE (i+j < strlen) AND (s[i] = s[j]) DO
j := j + replen;
END;
ok := ok AND (i+j >= strlen);
INC(i);
END;
IF ok THEN RETURN replen; END;
END;
RETURN 0;
END repLength;
 
(* Store the longest rep-string in the given buffer. *)
PROCEDURE repString(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR len: CARDINAL;
BEGIN
len := repLength(in);
Copy(in, 0, len, out);
out[len] := CHR(0);
END repString;
 
(* Display the longest rep-string given a string *)
PROCEDURE rep(s: ARRAY OF CHAR);
VAR buf: ARRAY [0..63] OF CHAR;
BEGIN
WriteString(s);
WriteString(": ");
repString(s, buf);
WriteString(buf);
WriteLn();
END rep;
 
(* Test cases *)
BEGIN
rep("1001110011");
rep("1110111011");
rep("0010010010");
rep("1010101010");
rep("1111111111");
rep("0100101101");
rep("0100100");
rep("101");
rep("11");
rep("00");
rep("1");
END RepStrings.</syntaxhighlight>
{{out}}
<pre>1001110011: 10011
1110111011: 1110
0010010010: 001
1010101010: 1010
1111111111: 11111
0100101101:
0100100: 010
101:
11: 1
00: 0
1:</pre>
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,333 ⟶ 2,902:
end w_
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,351 ⟶ 2,920:
=={{header|NGS}}==
{{trans|Python}}
<langsyntaxhighlight NGSlang="ngs">tests = [
'1001110011'
'1110111011'
Line 2,372 ⟶ 2,941:
echo("${test} ${if r "has repetition of length ${r} (i.e. ${test[0..r]})" "is not a rep-string"}")
})
}</langsyntaxhighlight>
{{out}}<pre>1001110011 has repetition of length 5 (i.e. 10011)
1110111011 has repetition of length 4 (i.e. 1110)
Line 2,387 ⟶ 2,956:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
proc isRepeated(text: string): int =
Line 2,408 ⟶ 2,977:
let ln = isRepeated(line)
echo "'", line, "' has a repetition length of ", ln, " i.e ",
(if ln > 0: "'" & line[0 ..< ln] & "'" else: "*not* a rep-string")</langsyntaxhighlight>
{{Out}}
<pre>'1001110011' has a repetition length of 5 i.e '10011'
Line 2,423 ⟶ 2,992:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class RepString {
function : Main(args : String[]) ~ Nil {
strings := ["1001110011", "1110111011", "0010010010", "1111111111",
Line 2,484 ⟶ 3,053:
return true;
}
}</langsyntaxhighlight>
 
Output:
Line 2,504 ⟶ 3,073:
Returns null if no rep string.
 
<langsyntaxhighlight lang="oforth">: repString(s)
| sz i |
s size dup ->sz 2 / 1 -1 step: i [
s left(sz i - ) s right(sz i -) == ifTrue: [ s left(i) return ]
]
null ;</langsyntaxhighlight>
 
{{Out}}
Line 2,519 ⟶ 3,088:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">rep(v)=for(i=1,#v\2,for(j=i+1,#v,if(v[j]!=v[j-i],next(2)));return(i));0;
v=["1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"];
for(i=1,#v,print(v[i]" "rep(Vec(v[i]))))</langsyntaxhighlight>
{{out}}
<pre>1001110011 5
Line 2,536 ⟶ 3,105:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">foreach (qw(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1)) {
print "$_\n";
if (/^(.+)\1+(.*$)(?(?{ substr($1, 0, length $2) eq $2 })|(?!))/) {
Line 2,543 ⟶ 3,112:
print " (no repeat)\n\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>1001110011
Line 2,581 ⟶ 3,150:
{{trans|Julia}}
Shows all possible repeated sub-strings, as Julia, but in the output style of Perl/Elixir
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">list_reps</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">replist</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 2,620 ⟶ 3,189:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,663 ⟶ 3,232:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def repstr /# s n -- s #/
Line 2,690 ⟶ 3,259:
len for
get repString print nl
endfor</langsyntaxhighlight>
{{out}}
<pre>1001110011: 10011
Line 2,705 ⟶ 3,274:
 
=== Press any key to exit ===</pre>
 
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Strings = [
"1001110011", % 10011
"1110111011", % 1110
"0010010010", % 001
"1010101010", % 1010
"1111111111", % 11111
"0100101101", % no solution
"0100100", % 010
"101", % no solution
"11", % 1
"00", % 0
"1", % no solution
"", % no solution
"123123123123123", % 123123
"12312312312312", % 123123
"123123123123124", % no solution
"abcabcdabcabcdabc", % abcabcd
[1,2,3,4,1,2,3,4,1,2,3] % 1,2,3,4
],
foreach(S in Strings)
printf("%w: ", S),
if maxrep(S,Substr,N) then
println([substr=Substr,n=N])
else
println("no solution")
end
end,
nl.
% the largest repeating substring
maxrep(S,Substr,N) =>
maxof(rep(S,Substr,N),N).
 
rep(S,Substr,N) =>
between(1,S.length div 2, N),
Len = S.length,
Len2 = Len - (Len mod N),
Substr = slice(S,1,N),
% count the number of proper slices
SS = [1 : I in 1..N..Len2, slice(S,I,I+N-1) = Substr],
SS.length = Len div N,
% the last (truncated) slice (or []) must be a substring of Substr
Rest = slice(S,Len2+1,Len),
find(Substr,Rest,1,_). </syntaxhighlight>
 
{{out}}
<pre>1001110011: [substr = 10011,n = 5]
1110111011: [substr = 1110,n = 4]
0010010010: [substr = 001,n = 3]
1010101010: [substr = 1010,n = 4]
1111111111: [substr = 11111,n = 5]
0100101101: no solution
0100100: [substr = 010,n = 3]
101: no solution
11: [substr = 1,n = 1]
00: [substr = 0,n = 1]
1: no solution
[]: no solution
123123123123123: [substr = 123123,n = 6]
12312312312312: [substr = 123123,n = 6]
123123123123124: no solution
abcabcdabcabcdabc: [substr = abcabcd,n = 7]
[1,2,3,4,1,2,3,4,1,2,3]: [substr = [1,2,3,4],n = 4]</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de repString (Str)
(let Lst (chop Str)
(for (N (/ (length Lst) 2) (gt0 N) (dec N))
Line 2,718 ⟶ 3,355:
(NIL (head X H))
(NIL Lst T) ) ) )
N ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(test 5 (repString "1001110011"))
(test 4 (repString "1110111011"))
(test 3 (repString "0010010010"))
Line 2,731 ⟶ 3,368:
(test 1 (repString "00"))
(test NIL (repString "1"))
(test NIL (repString "0100101"))</langsyntaxhighlight>
 
=={{header|PL/I}}==
{{Incorrect|PL/I|"0100101101" is not a rep-string.}}
<langsyntaxhighlight PLlang="pl/Ii">rep: procedure options (main); /* 5 May 2015 */
declare s bit (10) varying;
declare (i, k) fixed binary;
Line 2,753 ⟶ 3,390:
end;
 
end rep;</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,767 ⟶ 3,404:
00 is a rep-string containing 0
1 is not a rep-string
</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plmi">100H:
 
DECLARE MAX$REP LITERALLY '32';
DECLARE FALSE LITERALLY '0';
DECLARE TRUE LITERALLY '1';
DECLARE CR LITERALLY '0DH';
DECLARE LF LITERALLY '0AH';
 
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* PRINTS A BYTE AS A CHARACTER */
PRINT$CHAR: PROCEDURE( CH ); DECLARE CH BYTE; CALL BDOS( 2, CH ); END;
/* PRINTS A $ TERMINATED STRING */
PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
 
/* PRINTS A BYTE AS A NUMBER */
PRINT$BYTE: PROCEDURE( N );
DECLARE N BYTE;
DECLARE ( V, D2, D3 ) BYTE;
V = N;
D3 = V MOD 10;
IF ( V := V / 10 ) <> 0 THEN DO;
D2 = V MOD 10;
IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );
CALL PRINT$CHAR( '0' + D2 );
END;
CALL PRINT$CHAR( '0' + D3 );
END PRINT$BYTE;
/* PRINTS A FIXED LENGTH STRING */
PRINT$SUBSTRING: PROCEDURE( S$PTR, LEN );
DECLARE S$PTR ADDRESS, LEN BYTE, S BASED S$PTR ( MAX$REP )BYTE;
DECLARE S$POS BYTE;
DO S$POS = 0 TO LEN - 1;
CALL PRINT$CHAR( S( S$POS ) );
END;
END PRINT$SUBSTRING;
 
/* RETURNS THE LENGTH OF A $ TERMINATED STRING */
STR$LENGTH: PROCEDURE( S$PTR )BYTE;
DECLARE S$PTR ADDRESS, S BASED S$PTR ( MAX$REP )BYTE;
DECLARE RESULT BYTE;
RESULT = 0;
DO WHILE( S( RESULT ) <> '$' );
RESULT = RESULT + 1;
END;
RETURN RESULT;
END STR$LENGTH;
 
/* RETURNS THE LENGTH OF THE LONGEST REP-STRING IN S$PTR, */
LONGEST$REP$STRING: PROCEDURE( S$PTR )BYTE;
DECLARE S$PTR ADDRESS, S BASED S$PTR ( MAX$REP )BYTE;
DECLARE ( S$LEN, RESULT, S$POS, R$POS, I, FOUND ) BYTE;
RESULT = 0;
FOUND = FALSE;
S$LEN = STR$LENGTH( S$PTR );
S$POS = ( S$LEN / 2 ) - 1; /* IF ( S$LEN / 2 ) = 0, S$POS WILL BE 255 */
DO WHILE( NOT FOUND AND S$POS < 255 ); /* AS BYTE/ADDRESS ARE UNSIGNED */
/* CHECK THE POTENTIAL REP-STRING REPEATED A SUFFICIENT NUMBER */
/* OF TIMES (TRUNCATED IF NECESSARY) EQUALS THE ORIGINAL STRING */
FOUND = TRUE;
R$POS = S$POS + 1;
DO WHILE( FOUND AND R$POS < S$LEN AND FOUND );
I = 0;
DO WHILE( I <= S$POS AND R$POS < S$LEN AND FOUND );
FOUND = S( R$POS ) = S( I );
R$POS = R$POS + 1;
I = I + 1;
END;
END;
IF NOT FOUND THEN DO;
/* HAVEN'T FOUND A REP-STRING, TRY A SHORTER ONE */
S$POS = S$POS - 1; /* S$POS WILL BECOME 255 IF S$POS = 0 */
END;
END;
IF FOUND THEN DO;
RESULT = S$POS + 1;
END;
RETURN RESULT;
END LONGEST$REP$STRING;
 
DECLARE ( TEST$NUMBER, REP$STRING$LEN ) BYTE;
DECLARE TESTS ( 11 )ADDRESS;
TESTS( 0 ) = .'1001110011$';
TESTS( 1 ) = .'1110111011$';
TESTS( 2 ) = .'0010010010$';
TESTS( 3 ) = .'1010101010$';
TESTS( 4 ) = .'1111111111$';
TESTS( 5 ) = .'0100101101$';
TESTS( 6 ) = .'0100100$';
TESTS( 7 ) = .'101$';
TESTS( 8 ) = .'11$';
TESTS( 9 ) = .'00$';
TESTS( 10 ) = .'1$';
 
DO TEST$NUMBER = 0 TO LAST( TESTS );
REP$STRING$LEN = LONGEST$REP$STRING( TESTS( TEST$NUMBER ) );
CALL PRINT$STRING( TESTS( TEST$NUMBER ) );
IF REP$STRING$LEN = 0 THEN DO;
CALL PRINT$STRING( .': NO REP STRING$' );
END;
ELSE DO;
CALL PRINT$STRING( .': LONGEST REP STRING: $' );
CALL PRINT$SUBSTRING( TESTS( TEST$NUMBER ), REP$STRING$LEN );
END;
CALL PRINT$STRING( .( CR, LF, '$' ) );
END;
EOF</syntaxhighlight>
{{out}}
<pre>
1001110011: LONGEST REP STRING: 10011
1110111011: LONGEST REP STRING: 1110
0010010010: LONGEST REP STRING: 001
1010101010: LONGEST REP STRING: 1010
1111111111: LONGEST REP STRING: 11111
0100101101: NO REP STRING
0100100: LONGEST REP STRING: 010
101: NO REP STRING
11: LONGEST REP STRING: 1
00: LONGEST REP STRING: 0
1: NO REP STRING
</pre>
 
Line 2,773 ⟶ 3,533:
Using SWI-Prolog 7 library(func), for some functional syntax.
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(func)).
 
%% Implementation logic:
Line 2,804 ⟶ 3,564:
report_repstrings :-
Results = maplist(test_for_repstring) $ test_strings(~),
maplist(report_repstring, Results).</langsyntaxhighlight>
 
Output
Line 2,823 ⟶ 3,583:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">a$="1001110011"+#CRLF$+"1110111011"+#CRLF$+"0010010010"+#CRLF$+"1010101010"+#CRLF$+"1111111111"+#CRLF$+
"0100101101"+#CRLF$+"0100100" +#CRLF$+"101" +#CRLF$+"11" +#CRLF$+"00" +#CRLF$+
"1" +#CRLF$
Line 2,844 ⟶ 3,604:
If Not Len(s2$) : PrintN(LSet(s1$,15,Chr(32))+#TAB$+"found nothing.") : EndIf
Next
Input()</langsyntaxhighlight>
{{out}}
<pre>1001110011 longest sequence: 10011
Line 2,861 ⟶ 3,621:
 
===Python: Procedural===
<langsyntaxhighlight lang="python">def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
Line 2,883 ⟶ 3,643:
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))</langsyntaxhighlight>
 
{{out}}
Line 2,900 ⟶ 3,660:
===Python: Functional===
This returns all the possible repeated substrings
<langsyntaxhighlight lang="python">>>> def reps(text):
return [text[:x] for x in range(1, 1 + len(text) // 2)
if text.startswith(text[x:])]
Line 2,929 ⟶ 3,689:
'00' has reps ['0']
'1' has reps []
>>> </langsyntaxhighlight>
 
 
Line 2,935 ⟶ 3,695:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Rep-strings'''
 
from itertools import (accumulate, chain, cycle, islice)
Line 3,031 ⟶ 3,791:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Longest cycles:
Line 3,049 ⟶ 3,809:
===Python: Regexp===
This version, inspired by the Raku entry uses the regexp substitute where what the match is substituted with is returned by a function.
<langsyntaxhighlight lang="python">import re
 
matchstr = """\
Line 3,073 ⟶ 3,833:
print(re.sub(r'(.+)(\1+)(.*)|(.*)', _checker, txt))
 
checkit(matchstr)</langsyntaxhighlight>
 
{{out}}
Line 3,090 ⟶ 3,850:
===Python: find===
See [https://stackoverflow.com/questions/29481088/how-can-i-tell-if-a-string-repeats-itself-in-python/29489919#29489919 David Zhang's solution] to the same question posed on Stack Overflow.
 
=={{header|Quackery}}==
<code>factors</code> is defined at [http://rosettacode.org/wiki/Factors_of_an_integer#Quackery Factors of an integer].
 
<syntaxhighlight lang="quackery"> [ false swap
dup size 1 > if
[ [] temp put
dup size factors
-1 split drop
witheach
[ 2dup split drop
dip [ over size swap / ]
dup temp replace
swap of over = if
[ drop not
temp share
conclude ] ]
temp release ] swap ] is rep$ ( $ --> $ b )
 
[ dup rep$ iff
[ say 'The shortest rep-string in "'
swap echo$
say '" is "' echo$
say '".' ]
else
[ say 'There is no rep-string for "'
nip echo$ say '".' ]
cr ] is task ( $ --> )</syntaxhighlight>
 
{{out}}
 
<pre>The shortest rep-string in "1001110011" is "10011".
There is no rep-string for "1110111011".
There is no rep-string for "0010010010".
The shortest rep-string in "1010101010" is "10".
The shortest rep-string in "1111111111" is "1".
There is no rep-string for "0100101101".
There is no rep-string for "0100100".
There is no rep-string for "101".
The shortest rep-string in "11" is "1".
The shortest rep-string in "00" is "0".
There is no rep-string for "1".</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (rep-string str)
Line 3,117 ⟶ 3,919:
"00"
"1")])
(printf "~a => ~a\n" str (or (rep-string str) "not a rep-string")))</langsyntaxhighlight>
 
{{Out}}
Line 3,134 ⟶ 3,936:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>for <1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1> {
if /^ (.+) $0+: (.*$) <?{ $0.substr(0,$1.chars) eq $1 }> / {
my $rep = $0.chars;
Line 3,142 ⟶ 3,944:
say "$_ (no repeat)";
}
}</langsyntaxhighlight>
{{out}}
<pre>10011𝟙𝟘𝟘𝟙𝟙
Line 3,160 ⟶ 3,962:
throw away the bits on the right that you want thrown away.)
This produces the same output as above.
<syntaxhighlight lang="raku" perl6line>sub repstr(Str $s) {
my $bits = :2($s);
for reverse 1 .. $s.chars div 2 -> $left {
Line 3,176 ⟶ 3,978:
say "$_ (no repeat)";
}
}</langsyntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, ('1001110011') ('1110111011') ('0010010010')
('1010101010') ('1111111111') ('0100101101')
('0100100') ('101') ('11') ('00') ('1'): e.Tests
= <Each Show e.Tests>;
};
 
Each {
s.F = ;
s.F t.I e.R = <Mu s.F t.I> <Each s.F e.R>;
};
 
Show {
(e.S), <RepString e.S>: e.R = <Prout e.S ' => ' e.R>;
};
 
RepString {
() e.S = ;
(e.R) e.S, <Lengthen (e.R) e.S>: e.S e.X = e.R;
(e.R s.C) e.S = <RepString (e.R) e.S>;
e.S, <Lenw e.S>: s.L e.S,
<First <Div s.L 2> e.S>: (e.F) e.X
= <RepString (e.F) e.S>;
};
 
Lengthen {
(e.A) e.B, <Lenw e.A>: s.LA e.A,
<Lenw e.B>: s.LB e.B,
<Compare s.LA s.LB>: '-'
= <Lengthen (e.A e.A) e.B>;
(e.A) e.B, <Lenw e.B>: s.LB e.B,
<First s.LB e.A>: (e.FA) e.RA
= e.FA;
};</syntaxhighlight>
{{out}}
<pre>1001110011 => 10011
1110111011 => 1110
0010010010 => 001
1010101010 => 1010
1111111111 => 11111
0100101101 =>
0100100 => 010
101 =>
11 => 1
00 => 0
1 =></pre>
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 11.05.2013 Walter Pachl
* 14.05.2013 Walter Pachl extend to show additional rep-strings
Line 3,231 ⟶ 4,080:
show_norep:
Say right(sq,12) 'is not a repeated string'
Return</langsyntaxhighlight>
{{Out}}
<pre>'1001110011' has a repetition length of 5 i.e. '10011'
Line 3,252 ⟶ 4,101:
===version 2===
A check was added to validate if the strings are binary strings. &nbsp; The binary strings can be of any length.
<langsyntaxhighlight lang="rexx">/*REXX pgm determines if a string is a repString, it returns minimum length repString.*/
parse arg s /*get optional strings from the C.L. */
if s='' then s=1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 45
Line 3,267 ⟶ 4,116:
if left($$,L)==x then return @rep left($,15) "[length" j']'
end /*j*/ /* [↑] we have found a good repString.*/
return ' (no repetitions)' /*failure to find repString.*/</langsyntaxhighlight>
'''output''' &nbsp; when using the default binary strings for input:
<pre>
Line 3,285 ⟶ 4,134:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Rep-string
 
Line 3,316 ⟶ 4,165:
ok
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,330 ⟶ 4,179:
00 -> 0
1 -> (none)
</pre>
 
=={{header|RPL}}==
≪ DUP SIZE → in lin
≪ ""
'''IF''' lin 1 > '''THEN'''
lin 2 / FLOOR 1 '''FOR''' lrep
in 1 lrep SUB DUP
'''DO''' OVER + '''UNTIL''' DUP SIZE lin ≥ '''END'''
'''IF''' 1 lin SUB in == '''THEN''' SWAP 0 ‘lrep’ STO '''END'''
DROP
-1 '''STEP'''
'''END'''
≫ ≫ '<span style="color:blue">REPSTR</span>' STO
≪ { "1001110011" "1110111011" "0010010010" "1010101010" "1111111111" "0100101101" "0100100" "101" "11" "00" "1" }
{ } 1 3 PICK SIZE '''FOR''' j
OVER j GET <span style="color:blue">REPSTR</span> +
'''NEXT''' SWAP DROP
≫ 'TASK' STO
{{out}}
<pre>
1: { "10011" "1110" "001" "1010" "11111" "" "010" "" "1" "0" "" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">ar = %w(1001110011
1110111011
0010010010
Line 3,348 ⟶ 4,220:
rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]}
puts str, rep_pos ? " "*rep_pos + str[0, rep_pos] : "(no repetition)", ""
end</langsyntaxhighlight>
{{Out|Output (as Perl)}}
<pre>1001110011
Line 3,384 ⟶ 4,256:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn main() {
let strings = vec![
String::from("1001110011"),
Line 3,464 ⟶ 4,336:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object RepString extends App {
def repsOf(s: String) = s.trim match {
case s if s.length < 2 => Nil
Line 3,493 ⟶ 4,365:
val todo = if (args.length > 0) args else tests
todo.map(printReps).foreach(println)
}</langsyntaxhighlight>
{{out}}
<pre>1001110011: YES (10011)
Line 3,508 ⟶ 4,380:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: repeatLength (in string: text) is func
Line 3,537 ⟶ 4,409:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,553 ⟶ 4,425:
No rep-string for "1"
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program repstring;
tests := [
"1001110011", "1110111011", "0010010010", "1010101010",
"1111111111", "0100101101", "0100100", "101", "11", "00", "1"
];
 
loop for test in tests do
print(test + ": " + str repstrings(test));
end loop;
 
proc repstrings(s);
return {
s(..l) : l in [1..#s div 2]
| (s(..l)*(#s div l+1))(..#s) = s
};
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>1001110011: {'10011'}
1110111011: {'1110'}
0010010010: {'001'}
1010101010: {'10' '1010'}
1111111111: {'1' '11' '111' '1111' '11111'}
0100101101: {}
0100100: {'010'}
101: {}
11: {'1'}
00: {'0'}
1: {}</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = <1001110011 1110111011
0010010010 1010101010
1111111111 0100101101
Line 3,569 ⟶ 4,472:
say "#{n} (no repeat)";
}
}</langsyntaxhighlight>
{{out}}
<pre>10011𝟙𝟘𝟘𝟙𝟙
Line 3,584 ⟶ 4,487:
 
=={{header|Snobol4}}==
<langsyntaxhighlight Snobol4lang="snobol4">* Rep-string
strings = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 "
pat1 = (len(1) $ fc breakx(*fc)) $ x *x (arbno(*x) (rpos(0) | rem $ y *?(x ? y)))
Line 3,595 ⟶ 4,498:
:(getstring)
end
</syntaxhighlight>
</lang>
{{out}}
<pre>1001110011 has shortest rep-string value of -> 10011
Line 3,612 ⟶ 4,515:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func repString(_ input: String) -> [String] {
Line 3,637 ⟶ 4,540:
for testCase in testCases {
print("\(testCase) has reps: \(repString(testCase))")
}</langsyntaxhighlight>
 
{{out}}
Line 3,654 ⟶ 4,557:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc repstring {text} {
set len [string length $text]
for {set i [expr {$len/2}]} {$i > 0} {incr i -1} {
Line 3,664 ⟶ 4,567:
}
error "no repetition"
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">foreach sample {
"1001110011" "1110111011" "0010010010" "1010101010" "1111111111"
"0100101101" "0100100" "101" "11" "00" "1"
Line 3,677 ⟶ 4,580:
puts [format "\"%s\" is not a repeated string" $sample]
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,696 ⟶ 4,599:
{{trans|Tcl}}
{{works with|bash}}
<langsyntaxhighlight lang="bash">is_repeated() {
local str=$1 len rep part
for (( len = ${#str} / 2; len > 0; len-- )); do
Line 3,730 ⟶ 4,633:
00
1
END_TESTS</langsyntaxhighlight>
 
{{out}}
Line 3,746 ⟶ 4,649:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function rep_string(s)
max_len = Int(Len(s)/2)
Line 3,784 ⟶ 4,687:
WScript.StdOut.WriteLine
Next
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,799 ⟶ 4,702:
00: 0
1: No Repeating String
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn rep(s string) int {
for x := s.len / 2; x > 0; x-- {
if s.starts_with(s[x..]) {
return x
}
}
return 0
}
const m = '
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1'
fn main() {
for s in m.fields() {
n := rep(s)
if n > 0 {
println("$s $n rep-string ${s[..n]}")
} else {
println("$s not a rep-string")
}
}
}</syntaxhighlight>
 
{{out}}
<pre>
1001110011 5 rep-string 10011
1110111011 4 rep-string 1110
0010010010 3 rep-string 001
1010101010 4 rep-string 1010
1111111111 5 rep-string 11111
0100101101 not a rep-string
0100100 3 rep-string 010
101 not a rep-string
11 1 rep-string 1
00 1 rep-string 0
1 not a rep-string
</pre>
 
Line 3,804 ⟶ 4,757:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var repString = Fn.new { |s|
Line 3,839 ⟶ 4,792:
var t = (reps.count > 0) ? reps[-1] : "Not a rep-string"
Fmt.print("$10s -> $s", s, t)
}</langsyntaxhighlight>
 
{{out}}
Line 3,859 ⟶ 4,812:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">data "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", ""
 
sub rep$(c$, n)
Line 3,885 ⟶ 4,838:
print p$, " is composed of ", b$, " repeated"
end if
loop</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn repString(s){
foreach n in ([s.len()/2+1..1,-1]){
Walker.cycle(s[0,n]).pump(s.len(),String) :
Line 3,895 ⟶ 4,848:
}
return(False)
}</langsyntaxhighlight>
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn repString(s){
foreach n in ([s.len()/2..0,-1]){
if(s.matches(s[n,*] + "*") and n*2<=s.len()) return(n);
}
return(False)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">words:=("1001110011 1110111011 0010010010 1010101010 "
"1111111111 0100101101 0100100 101 11 00 1").split(" ");
foreach w in (words){
Line 3,909 ⟶ 4,862:
else [0..*,n].tweak('wrap(z){ if(s:=w[z,n]) s else Void.Stop })
.walk().concat(" ").println();
}</langsyntaxhighlight>
{{out}}
<pre>
3,037

edits