Look-and-say sequence: Difference between revisions

Content added Content deleted
m (→‎{{header|Picat}}: Added {{out}})
m (syntax highlighting fixup automation)
Line 42: Line 42:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F lookandsay(=number)
<syntaxhighlight lang="11l">F lookandsay(=number)
V result = ‘’
V result = ‘’
V repeat = number[0]
V repeat = number[0]
Line 61: Line 61:
L 10
L 10
print(num)
print(num)
num = lookandsay(num)</lang>
num = lookandsay(num)</syntaxhighlight>


{{out}}
{{out}}
Line 80: Line 80:




<lang 8080asm>bdos: equ 5 ; CP/M calls
<syntaxhighlight lang="8080asm">bdos: equ 5 ; CP/M calls
puts: equ 9
puts: equ 9


Line 163: Line 163:
; Due to how CP/M loads programs, the memory after here
; Due to how CP/M loads programs, the memory after here
; is free until we hit the stack.
; is free until we hit the stack.
</syntaxhighlight>
</lang>


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==


<lang asm> bits 16
<syntaxhighlight lang="asm"> bits 16
cpu 8086
cpu 8086
puts: equ 9h ; MS/DOS system call to print a string
puts: equ 9h ; MS/DOS system call to print a string
Line 220: Line 220:
section .data
section .data
newline: db 13,10,'$' ; Newline to print in between members
newline: db 13,10,'$' ; Newline to print in between members
memb: db '1$' ; This is where the current member is stored</lang>
memb: db '1$' ; This is where the current member is stored</syntaxhighlight>




=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE FUNC GetLength(CHAR ARRAY s BYTE pos)
<syntaxhighlight lang="action!">BYTE FUNC GetLength(CHAR ARRAY s BYTE pos)
CHAR c
CHAR c
BYTE len
BYTE len
Line 288: Line 288:
FI
FI
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Look-and-say_sequence.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Look-and-say_sequence.png Screenshot from Atari 8-bit computer]
Line 307: Line 307:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO, Ada.Strings.Fixed;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;


Line 319: Line 319:
end loop;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";</lang>
end "+";</syntaxhighlight>
This function can be used as follows:
This function can be used as follows:
<lang ada>Put_Line (+"1");
<syntaxhighlight lang="ada">Put_Line (+"1");
Put_Line (+(+"1"));
Put_Line (+(+"1"));
Put_Line (+(+(+"1")));
Put_Line (+(+(+"1")));
Line 330: Line 330:
Put_Line (+(+(+(+(+(+(+(+"1"))))))));
Put_Line (+(+(+(+(+(+(+(+"1"))))))));
Put_Line (+(+(+(+(+(+(+(+(+"1")))))))));
Put_Line (+(+(+(+(+(+(+(+(+"1")))))))));
Put_Line (+(+(+(+(+(+(+(+(+(+"1"))))))))));</lang>
Put_Line (+(+(+(+(+(+(+(+(+(+"1"))))))))));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 350: Line 350:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>OP + = (STRING s)STRING:
<syntaxhighlight lang="algol68">OP + = (STRING s)STRING:
BEGIN
BEGIN
CHAR item = s[LWB s];
CHAR item = s[LWB s];
Line 376: Line 376:
print ((+(+(+(+(+(+(+(+"1"))))))), new line));
print ((+(+(+(+(+(+(+(+"1"))))))), new line));
print ((+(+(+(+(+(+(+(+(+"1")))))))), new line));
print ((+(+(+(+(+(+(+(+(+"1")))))))), new line));
print ((+(+(+(+(+(+(+(+(+(+"1"))))))))), new line))</lang>
print ((+(+(+(+(+(+(+(+(+(+"1"))))))))), new line))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 392: Line 392:


=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
<lang algolm>begin
<syntaxhighlight lang="algolm">begin
string(1) function digit(n);
string(1) function digit(n);
integer n;
integer n;
Line 430: Line 430:
curlen := j - 1;
curlen := j - 1;
end;
end;
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 449: Line 449:


=={{header|APL}}==
=={{header|APL}}==
<lang apl>
<syntaxhighlight lang="apl">
⎕IO←0
⎕IO←0
d←{(1↓⍵)-¯1↓⍵}
d←{(1↓⍵)-¯1↓⍵}
f←{m←(0≠d ⍵),1 ⋄ ,(d ¯1,m/⍳⍴⍵),[.5](m/⍵)}
f←{m←(0≠d ⍵),1 ⋄ ,(d ¯1,m/⍳⍴⍵),[.5](m/⍵)}
{(f⍣⍵) ,1}¨⍳10
{(f⍣⍵) ,1}¨⍳10
</syntaxhighlight>
</lang>




This is an ugly little APL2 function that accepts a numeric vector (or scalar) and returns the result.
This is an ugly little APL2 function that accepts a numeric vector (or scalar) and returns the result.
Apologies for the labeled loop...
Apologies for the labeled loop...
<lang apl2>
<syntaxhighlight lang="apl2">
R←LNS V;T
R←LNS V;T
R←0⍴0 ⍝ initiate empty reply
R←0⍴0 ⍝ initiate empty reply
Line 465: Line 465:
R←R,T,↑V ⍝ append t and the 1st digit
R←R,T,↑V ⍝ append t and the 1st digit
→(0≠↑⍴V←T↓V)/LOOP ⍝ drop t digits and iterate
→(0≠↑⍴V←T↓V)/LOOP ⍝ drop t digits and iterate
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>on lookAndSay(startNumber, howMany)
<syntaxhighlight lang="applescript">on lookAndSay(startNumber, howMany)
if (howMany < 1) then return {}
if (howMany < 1) then return {}
Line 515: Line 515:


-- Test code:
-- Test code:
return lookAndSay(1, 10)</lang>
return lookAndSay(1, 10)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{"1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211", "31131211131221", "13211311123113112211"}</lang>
<syntaxhighlight lang="applescript">{"1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211", "31131211131221", "13211311123113112211"}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>lookAndSay: function [n][
<syntaxhighlight lang="rebol">lookAndSay: function [n][
if n=0 -> return "1"
if n=0 -> return "1"
previous: lookAndSay n-1
previous: lookAndSay n-1
Line 545: Line 545:
loop 0..10 'x [
loop 0..10 'x [
print [x "->" lookAndSay x]
print [x "->" lookAndSay x]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 562: Line 562:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>AutoExecute:
<syntaxhighlight lang="autohotkey">AutoExecute:
Gui, -MinimizeBox
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Edit, w500 r20 vInput, 1
Line 598: Line 598:
}
}
Return, r c d
Return, r c d
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>function lookandsay(a)
<syntaxhighlight lang="awk">function lookandsay(a)
{
{
s = ""
s = ""
Line 627: Line 627:
print b
print b
}
}
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang BASIC>10 DEFINT A-Z: I$="1"
<syntaxhighlight lang="basic">10 DEFINT A-Z: I$="1"
20 FOR Z=1 TO 15
20 FOR Z=1 TO 15
30 PRINT I$
30 PRINT I$
Line 641: Line 641:
100 NEXT I
100 NEXT I
110 I$=O$
110 I$=O$
120 NEXT Z</lang>
120 NEXT Z</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 660: Line 660:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
# look and say
# look and say


Line 686: Line 686:
print a$[j]
print a$[j]
next n
next n
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> number$ = "1"
<syntaxhighlight lang="bbcbasic"> number$ = "1"
FOR i% = 1 TO 10
FOR i% = 1 TO 10
number$ = FNlooksay(number$)
number$ = FNlooksay(number$)
Line 708: Line 708:
i% = j%
i% = j%
UNTIL i% > LEN(n$)
UNTIL i% > LEN(n$)
= o$</lang>
= o$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 724: Line 724:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


manifest $(
manifest $(
Line 774: Line 774:
move(buf1,buf2)
move(buf1,buf2)
$)
$)
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 793: Line 793:


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>LookSay ← ∾´((⊑∾˜ ≠+'0'˙)¨1↓((+`»≠⊢)⊸⊔))
<syntaxhighlight lang="bqn">LookSay ← ∾´((⊑∾˜ ≠+'0'˙)¨1↓((+`»≠⊢)⊸⊔))


>((⌈´≠¨)↑¨⊢) LookSay⍟(↕15)"1"</lang>
>((⌈´≠¨)↑¨⊢) LookSay⍟(↕15)"1"</syntaxhighlight>
{{out}}
{{out}}
<pre>┌─
<pre>┌─
Line 817: Line 817:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
In this example we use a non-linear pattern and a negation of a pattern: the end of e sequence of equal digits is (1) the end of the string or (2) the start of a sequence starting with a different digit.
In this example we use a non-linear pattern and a negation of a pattern: the end of e sequence of equal digits is (1) the end of the string or (2) the start of a sequence starting with a different digit.
<lang bracmat>( 1:?number
<syntaxhighlight lang="bracmat">( 1:?number
& 0:?lines
& 0:?lines
& whl
& whl
Line 839: Line 839:
)
)
)
)
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>11
<pre>11
Line 854: Line 854:
=={{header|C}}==
=={{header|C}}==
This program will not stop until killed or running out of memory.
This program will not stop until killed or running out of memory.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 875: Line 875:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Text;
using System.Text;
using System.Linq;
using System.Linq;
Line 917: Line 917:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 932: Line 932:


Alternate version using Regex (C#2 syntax only):
Alternate version using Regex (C#2 syntax only):
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
Line 972: Line 972:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}} (with args: 1 15):
{{out}} (with args: 1 15):
<pre>1
<pre>1
Line 991: Line 991:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <sstream>
#include <string>
#include <string>
Line 1,020: Line 1,020:
std::cout << laf << '\n';
std::cout << laf << '\n';
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
function lookAndSay(Integer|String input) {
function lookAndSay(Integer|String input) {
Line 1,050: Line 1,050:
print(result);
print(result);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
No ugly int-to-string-and-back conversions.
No ugly int-to-string-and-back conversions.


<lang clojure>(defn digits-seq
<syntaxhighlight lang="clojure">(defn digits-seq
"Returns a seq of the digits of a number (L->R)."
"Returns a seq of the digits of a number (L->R)."
[n]
[n]
Line 1,070: Line 1,070:
(defn look-and-say [n]
(defn look-and-say [n]
(->> n digits-seq (partition-by identity)
(->> n digits-seq (partition-by identity)
(mapcat (juxt count first)) join-digits))</lang>
(mapcat (juxt count first)) join-digits))</syntaxhighlight>
{{out}}
{{out}}
<lang clojure>user> (take 8 (iterate look-and-say 1))
<syntaxhighlight lang="clojure">user> (take 8 (iterate look-and-say 1))
(1 11 21 1211 111221 312211 13112221 1113213211)</lang>
(1 11 21 1211 111221 312211 13112221 1113213211)</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>look_and_say = proc (s: string) returns (string)
<syntaxhighlight lang="clu">look_and_say = proc (s: string) returns (string)
out: array[char] := array[char]$[]
out: array[char] := array[char]$[]
count: int := 0
count: int := 0
Line 1,109: Line 1,109:
cur := look_and_say(cur)
cur := look_and_say(cur)
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,128: Line 1,128:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. LOOK-AND-SAY-SEQ.
PROGRAM-ID. LOOK-AND-SAY-SEQ.
Line 1,170: Line 1,170:
SUBTRACT 1 FROM STEP-AMOUNT.
SUBTRACT 1 FROM STEP-AMOUNT.
IF STEP-AMOUNT IS NOT EQUAL TO ZERO GO TO LOOK-AND-SAY.
IF STEP-AMOUNT IS NOT EQUAL TO ZERO GO TO LOOK-AND-SAY.
STOP RUN.</lang>
STOP RUN.</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,188: Line 1,188:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun compress (array &key (test 'eql) &aux (l (length array)))
<syntaxhighlight lang="lisp">(defun compress (array &key (test 'eql) &aux (l (length array)))
"Compresses array by returning a list of conses each of whose car is
"Compresses array by returning a list of conses each of whose car is
a number of occurrences and whose cdr is the element occurring. For
a number of occurrences and whose cdr is the element occurring. For
Line 1,206: Line 1,206:
(parse-integer (string (cdr pair)))))
(parse-integer (string (cdr pair)))))
(compress (princ-to-string number))
(compress (princ-to-string number))
:initial-value 0))</lang>
:initial-value 0))</syntaxhighlight>


Example use:
Example use:


<lang lisp>(next-look-and-say 9887776666) ;=> 19283746</lang>
<syntaxhighlight lang="lisp">(next-look-and-say 9887776666) ;=> 19283746</syntaxhighlight>


Straight character counting:
Straight character counting:
<lang lisp>(defun look-and-say (s)
<syntaxhighlight lang="lisp">(defun look-and-say (s)
(let ((out (list (char s 0) 0)))
(let ((out (list (char s 0) 0)))
(loop for x across s do
(loop for x across s do
Line 1,223: Line 1,223:
(loop for s = "1" then (look-and-say s)
(loop for s = "1" then (look-and-say s)
repeat 10
repeat 10
do (write-line s))</lang>
do (write-line s))</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "strings.coh";


Line 1,270: Line 1,270:
CopyString(&nextbuf as [uint8], &curbuf as [uint8]);
CopyString(&nextbuf as [uint8], &curbuf as [uint8]);
members := members - 1;
members := members - 1;
end loop;</lang>
end loop;</syntaxhighlight>


{{out}}
{{out}}
Line 1,294: Line 1,294:
{{trans|Ruby}}
{{trans|Ruby}}
The simplest one:
The simplest one:
<lang ruby>class String
<syntaxhighlight lang="ruby">class String
def lookandsay
def lookandsay
gsub(/(.)\1*/){ |s| s.size.to_s + s[0] }
gsub(/(.)\1*/){ |s| s.size.to_s + s[0] }
Line 1,301: Line 1,301:
ss = '1'
ss = '1'
12.times { puts ss; ss = ss.to_s.lookandsay }</lang>
12.times { puts ss; ss = ss.to_s.lookandsay }</syntaxhighlight>


{{trans|Ruby from Perl}}
{{trans|Ruby from Perl}}
<lang ruby>def lookandsay(str)
<syntaxhighlight lang="ruby">def lookandsay(str)
str.gsub(/(.)\1*/) { |s| s.size.to_s + $1 }
str.gsub(/(.)\1*/) { |s| s.size.to_s + $1 }
end
end
num = "1"
num = "1"
12.times { puts num; num = lookandsay(num) }</lang>
12.times { puts num; num = lookandsay(num) }</syntaxhighlight>


{{trans|Ruby}}
{{trans|Ruby}}
Using Enumerable#chunks
Using Enumerable#chunks
<lang ruby>def lookandsay(str)
<syntaxhighlight lang="ruby">def lookandsay(str)
str.chars.chunks(&.itself).map{ |(c, x)| x.size.to_s + c }.join
str.chars.chunks(&.itself).map{ |(c, x)| x.size.to_s + c }.join
end
end
num = "1"
num = "1"
12.times { puts num; num = lookandsay(num) }</lang>
12.times { puts num; num = lookandsay(num) }</syntaxhighlight>


{{out}}
{{out}}
Line 1,337: Line 1,337:
=={{header|D}}==
=={{header|D}}==
===Short Functional Version===
===Short Functional Version===
<lang d>import std.stdio, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;


enum say = (in string s) pure => s.group.map!q{ text(a[1],a[0]) }.join;
enum say = (in string s) pure => s.group.map!q{ text(a[1],a[0]) }.join;
Line 1,343: Line 1,343:
void main() {
void main() {
"1".recurrence!((t, n) => t[n - 1].say).take(8).writeln;
"1".recurrence!((t, n) => t[n - 1].say).take(8).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>["1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211"]</pre>
<pre>["1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211"]</pre>


===Beginner Imperative Version===
===Beginner Imperative Version===
<lang d>import std.stdio, std.conv, std.array;
<syntaxhighlight lang="d">import std.stdio, std.conv, std.array;


pure string lookAndSay(string s){
pure string lookAndSay(string s){
Line 1,364: Line 1,364:
for(auto i=0; i<10; i++)
for(auto i=0; i<10; i++)
(s = s.lookAndSay).writeln;
(s = s.lookAndSay).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>11
<pre>11
Line 1,378: Line 1,378:


===Fast Imperative Version===
===Fast Imperative Version===
<lang d>import core.stdc.stdio, std.math, std.conv, std.algorithm, std.array;
<syntaxhighlight lang="d">import core.stdc.stdio, std.math, std.conv, std.algorithm, std.array;


void showLookAndSay(bool showArrays)(in uint n) nothrow {
void showLookAndSay(bool showArrays)(in uint n) nothrow {
Line 1,471: Line 1,471:
immutable n = (args.length == 2) ? args[1].to!uint : 10;
immutable n = (args.length == 2) ? args[1].to!uint : 10;
n.showLookAndSay!true;
n.showLookAndSay!true;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Allocated 116 bytes.
<pre>Allocated 116 bytes.
Line 1,488: Line 1,488:


With:
With:
<lang d>70.showLookAndSay!false;</lang>
<syntaxhighlight lang="d">70.showLookAndSay!false;</syntaxhighlight>
{{out}}
{{out}}
<pre>Allocated 158045069 bytes.
<pre>Allocated 158045069 bytes.
Line 1,514: Line 1,514:
===Intermediate Version===
===Intermediate Version===
This mostly imperative version is intermediate in both speed and code size:
This mostly imperative version is intermediate in both speed and code size:
<lang d>void main(in string[] args) {
<syntaxhighlight lang="d">void main(in string[] args) {
import std.stdio, std.conv, std.algorithm, std.array, std.string;
import std.stdio, std.conv, std.algorithm, std.array, std.string;


Line 1,532: Line 1,532:
writefln("%2d: n. digits: %d", i, seq.length);
writefln("%2d: n. digits: %d", i, seq.length);
}
}
}</lang>
}</syntaxhighlight>
The output is the same as the second version.
The output is the same as the second version.


Line 1,549: Line 1,549:
This recursive version is able to generate very large sequences in a short time without memory for the intermediate sequence (and with stack space proportional to the sequence order).
This recursive version is able to generate very large sequences in a short time without memory for the intermediate sequence (and with stack space proportional to the sequence order).


<lang d>import core.stdc.stdio, std.conv;
<syntaxhighlight lang="d">import core.stdc.stdio, std.conv;


// On Windows this uses the printf from the Microsoft C runtime,
// On Windows this uses the printf from the Microsoft C runtime,
Line 1,685: Line 1,685:
evolve(39, n - base);
evolve(39, n - base);
'\n'.putchar;
'\n'.putchar;
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 1,691: Line 1,691:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>\util.g
<syntaxhighlight lang="draco">\util.g


proc nonrec look_and_say(*char inp, outp) void:
proc nonrec look_and_say(*char inp, outp) void:
Line 1,722: Line 1,722:
CharsCopy(&buf1[0], &buf2[0])
CharsCopy(&buf1[0], &buf2[0])
od
od
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,740: Line 1,740:


=={{header|E}}==
=={{header|E}}==
<lang e>def lookAndSayNext(number :int) {
<syntaxhighlight lang="e">def lookAndSayNext(number :int) {
var seen := null
var seen := null
var count := 0
var count := 0
Line 1,765: Line 1,765:
println(number)
println(number)
number := lookAndSayNext(number)
number := lookAndSayNext(number)
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'math) ;; for (number->list) = explode function
(lib 'math) ;; for (number->list) = explode function
(lib 'list) ;; (group)
(lib 'list) ;; (group)
Line 1,782: Line 1,782:
(next L)))
(next L)))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang="scheme">
(task 10 1)
(task 10 1)
1
1
Line 1,796: Line 1,796:
31131211131221
31131211131221
13211311123113112211
13211311123113112211
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule LookAndSay do
<syntaxhighlight lang="elixir">defmodule LookAndSay do
def next(n) do
def next(n) do
Enum.chunk_by(to_char_list(n), &(&1))
Enum.chunk_by(to_char_list(n), &(&1))
Line 1,821: Line 1,821:
end
end


LookAndSay.main(System.argv)</lang>
LookAndSay.main(System.argv)</syntaxhighlight>


{{out}}
{{out}}
Line 1,827: Line 1,827:


'''Regex version:'''
'''Regex version:'''
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def look_and_say(n) do
def look_and_say(n) do
Regex.replace(~r/(.)\1*/, to_string(n), fn x,y -> [to_string(String.length(x)),y] end)
Regex.replace(~r/(.)\1*/, to_string(n), fn x,y -> [to_string(String.length(x)),y] end)
Line 1,834: Line 1,834:
end
end


IO.inspect Enum.reduce(1..9, [1], fn _,acc -> [RC.look_and_say(hd(acc)) | acc] end) |> Enum.reverse</lang>
IO.inspect Enum.reduce(1..9, [1], fn _,acc -> [RC.look_and_say(hd(acc)) | acc] end) |> Enum.reverse</syntaxhighlight>


{{out}}
{{out}}
Line 1,843: Line 1,843:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(str).
<syntaxhighlight lang="erlang">-module(str).
-export([look_and_say/1, look_and_say/2]).
-export([look_and_say/1, look_and_say/2]).


Line 1,860: Line 1,860:
look_and_say(T, H, N+1, Acc);
look_and_say(T, H, N+1, Acc);
look_and_say([H|T], Current, N, Acc) ->
look_and_say([H|T], Current, N, Acc) ->
look_and_say(T, H, 1, [Current, $0+N | Acc]).</lang>
look_and_say(T, H, 1, [Current, $0+N | Acc]).</syntaxhighlight>


{{out}}
{{out}}
Line 1,876: Line 1,876:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
PROGRAM LOOK
PROGRAM LOOK


Line 1,901: Line 1,901:
END FOR
END FOR
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
<pre>
<pre>
11
11
Line 1,917: Line 1,917:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Library functions somehow missing in F# out of the box (but present in haskell)
Library functions somehow missing in F# out of the box (but present in haskell)
<lang fsharp>
<syntaxhighlight lang="fsharp">
let rec brk p lst =
let rec brk p lst =
match lst with
match lst with
Line 1,938: Line 1,938:


let group lst : list<list<'a>> when 'a : equality = groupBy (=) lst
let group lst : list<list<'a>> when 'a : equality = groupBy (=) lst
</syntaxhighlight>
</lang>


Implementation
Implementation
<lang fsharp>
<syntaxhighlight lang="fsharp">
let lookAndSay =
let lookAndSay =
let describe (xs: char list) =
let describe (xs: char list) =
Line 1,952: Line 1,952:


Seq.take 10 lookAndSay
Seq.take 10 lookAndSay
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: (look-and-say) ( str -- )
<syntaxhighlight lang="factor">: (look-and-say) ( str -- )
unclip-slice swap [ 1 ] 2dip [
unclip-slice swap [ 1 ] 2dip [
2dup = [ drop [ 1 + ] dip ] [
2dup = [ drop [ 1 + ] dip ] [
Line 1,964: Line 1,964:
: look-and-say ( str -- str' ) [ (look-and-say) ] "" make ;
: look-and-say ( str -- str' ) [ (look-and-say) ] "" make ;


"1" 10 [ dup print look-and-say ] times print</lang>
"1" 10 [ dup print look-and-say ] times print</syntaxhighlight>


=={{header|Fennel}}==
=={{header|Fennel}}==
<lang fennel>(fn look-and-say [t]
<syntaxhighlight lang="fennel">(fn look-and-say [t]
(let [lst t
(let [lst t
ret []]
ret []]
Line 1,983: Line 1,983:
(for [i 1 10]
(for [i 1 10]
(print (table.concat lst))
(print (table.concat lst))
(set lst (look-and-say lst)))</lang>
(set lst (look-and-say lst)))</syntaxhighlight>
Alternative solution
Alternative solution
<lang fennel>(fn look-and-say [s]
<syntaxhighlight lang="fennel">(fn look-and-say [s]
(var ret [])
(var ret [])
(var (num cnt) (values (s:sub 1 1) 1))
(var (num cnt) (values (s:sub 1 1) 1))
Line 2,002: Line 2,002:
(for [i 1 10]
(for [i 1 10]
(print str)
(print str)
(set str (look-and-say str)))</lang>
(set str (look-and-say str)))</syntaxhighlight>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang focal>01.10 A "HOW MANY",M
<syntaxhighlight lang="focal">01.10 A "HOW MANY",M
01.20 S B(0)=1;S B(1)=0
01.20 S B(0)=1;S B(1)=0
01.30 F Z=1,M;D 4;D 2
01.30 F Z=1,M;D 4;D 2
Line 2,037: Line 2,037:
04.40 D 3
04.40 D 3
04.50 S X=X+1
04.50 S X=X+1
04.60 G 4.2</lang>
04.60 G 4.2</syntaxhighlight>
{{out}}
{{out}}
<pre>HOW MANY:12
<pre>HOW MANY:12
Line 2,054: Line 2,054:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>create buf1 256 allot
<syntaxhighlight lang="forth">create buf1 256 allot
create buf2 256 allot
create buf2 256 allot
buf1 value src
buf1 value src
Line 2,081: Line 2,081:
0 do next-look-and-say cr src count type loop ;
0 do next-look-and-say cr src count type loop ;


10 look-and-say</lang>
10 look-and-say</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>module LookAndSay
<syntaxhighlight lang="fortran">module LookAndSay
implicit none
implicit none


Line 2,114: Line 2,114:
end subroutine look_and_say
end subroutine look_and_say


end module LookAndSay</lang>
end module LookAndSay</syntaxhighlight>


<lang fortran>program LookAndSayTest
<syntaxhighlight lang="fortran">program LookAndSayTest
use LookAndSay
use LookAndSay
implicit none
implicit none
Line 2,132: Line 2,132:
end do
end do
end program LookAndSayTest</lang>
end program LookAndSayTest</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|BASIC256}}
{{trans|BASIC256}}
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As Integer n, j, k, k0, r
Dim As Integer n, j, k, k0, r
Dim As String X(2)
Dim As String X(2)
Line 2,162: Line 2,162:
Next n
Next n
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,181: Line 2,181:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
LookAndSay = "12211123"
LookAndSay = "12211123"
println["Starting Value: " + LookAndSay]
println["Starting Value: " + LookAndSay]
Line 2,206: Line 2,206:
println["$i - $LookAndSay"]
println["$i - $LookAndSay"]
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,226: Line 2,226:


'''[https://gambas-playground.proko.eu/?gist=83d63e1706fa1dc3c7468b1e9d7bcf05 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=83d63e1706fa1dc3c7468b1e9d7bcf05 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim i, j, cnt As Integer
Dim i, j, cnt As Integer
Dim txt$, curr$, result$ As String
Dim txt$, curr$, result$ As String
Line 2,250: Line 2,250:
Dec i
Dec i
Until i <= 0
Until i <= 0
End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,257: Line 2,257:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>LookAndSay := function(s)
<syntaxhighlight lang="gap">LookAndSay := function(s)
local c, r, cur, ncur, v;
local c, r, cur, ncur, v;
v := "123";
v := "123";
Line 2,293: Line 2,293:
LookAndSay(last); # "1321132132111213122112311311222113111221131221"
LookAndSay(last); # "1321132132111213122112311311222113111221131221"
LookAndSay(last); # "11131221131211131231121113112221121321132132211331222113112211"
LookAndSay(last); # "11131221131211131231121113112221121321132132211331222113112211"
LookAndSay(last); # "311311222113111231131112132112311321322112111312211312111322212311322113212221"</lang>
LookAndSay(last); # "311311222113111231131112132112311321322112111312211312111322212311322113212221"</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,326: Line 2,326:
fmt.Println(s)
fmt.Println(s)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,341: Line 2,341:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def lookAndSay(sequence) {
<syntaxhighlight lang="groovy">def lookAndSay(sequence) {
def encoded = new StringBuilder()
def encoded = new StringBuilder()
(sequence.toString() =~ /(([0-9])\2*)/).each { matcher ->
(sequence.toString() =~ /(([0-9])\2*)/).each { matcher ->
Line 2,347: Line 2,347:
}
}
encoded.toString()
encoded.toString()
}</lang>
}</syntaxhighlight>
Test Code
Test Code
<lang groovy>def sequence = "1"
<syntaxhighlight lang="groovy">def sequence = "1"
(1..12).each {
(1..12).each {
println sequence
println sequence
sequence = lookAndSay(sequence)
sequence = lookAndSay(sequence)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 2,369: Line 2,369:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad (liftM2)
<syntaxhighlight lang="haskell">import Control.Monad (liftM2)
import Data.List (group)
import Data.List (group)


Line 2,393: Line 2,393:
where describe run = show (length run) ++ take 1 run
where describe run = show (length run) ++ take 1 run


main = mapM_ print (iterate lookAndSay 1) -- display sequence until interrupted</lang>
main = mapM_ print (iterate lookAndSay 1) -- display sequence until interrupted</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
<lang haxe>using Std;
<syntaxhighlight lang="haxe">using Std;


class Main
class Main
Line 2,434: Line 2,434:
return results;
return results;
}
}
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every 1 to 10 do
every 1 to 10 do
write(n := nextlooknsayseq(\n | 1))
write(n := nextlooknsayseq(\n | 1))
Line 2,450: Line 2,450:
}
}
return n2
return n2
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,467: Line 2,467:
'''Solution''':
'''Solution''':


<lang j>las=: ,@((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)@]^:(1+i.@[)</lang>
<syntaxhighlight lang="j">las=: ,@((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)@]^:(1+i.@[)</syntaxhighlight>


'''Example''':
'''Example''':
<lang j> 10 las 1
<syntaxhighlight lang="j"> 10 las 1
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221</lang>
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221</syntaxhighlight>


Note the result is an actual numeric sequence (cf. the textual solutions given in other languages).
Note the result is an actual numeric sequence (cf. the textual solutions given in other languages).
Line 2,478: Line 2,478:
{{trans|C#}}
{{trans|C#}}
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>public static String lookandsay(String number){
<syntaxhighlight lang="java5">public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
StringBuilder result= new StringBuilder();


Line 2,495: Line 2,495:
}
}
return result.toString();
return result.toString();
}</lang>
}</syntaxhighlight>
Testing:
Testing:
<lang java5>public static void main(String[] args){
<syntaxhighlight lang="java5">public static void main(String[] args){
String num = "1";
String num = "1";
Line 2,504: Line 2,504:
num = lookandsay(num);
num = lookandsay(num);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 2,520: Line 2,520:
=== With RegExp ===
=== With RegExp ===
{{trans|Perl}}
{{trans|Perl}}
<lang javascript>function lookandsay(str) {
<syntaxhighlight lang="javascript">function lookandsay(str) {
return str.replace(/(.)\1*/g, function(seq, p1){return seq.length.toString() + p1})
return str.replace(/(.)\1*/g, function(seq, p1){return seq.length.toString() + p1})
}
}
Line 2,528: Line 2,528:
alert(num);
alert(num);
num = lookandsay(num);
num = lookandsay(num);
}</lang>
}</syntaxhighlight>


=== Imperative version ===
=== Imperative version ===
<lang javascript>function lookAndSay( s="" ){
<syntaxhighlight lang="javascript">function lookAndSay( s="" ){
var tokens=[]
var tokens=[]
var i=0, j=1
var i=0, j=1
Line 2,543: Line 2,543:
var phrase="1"
var phrase="1"
for(var n=0; n<10; n++ )
for(var n=0; n<10; n++ )
console.log( phrase = lookAndSay( phrase ) )</lang>
console.log( phrase = lookAndSay( phrase ) )</syntaxhighlight>
{{Output}}
{{Output}}
<pre>11
<pre>11
Line 2,558: Line 2,558:
=={{header|jq}}==
=={{header|jq}}==
{{Works with|jq|1.4}}
{{Works with|jq|1.4}}
<lang jq>def look_and_say:
<syntaxhighlight lang="jq">def look_and_say:
def head(c; n): if .[n:n+1] == c then head(c; n+1) else n end;
def head(c; n): if .[n:n+1] == c then head(c; n+1) else n end;
tostring
tostring
Line 2,572: Line 2,572:
else look_and_say as $lns
else look_and_say as $lns
| $lns, ($lns|look_and_say(n-1))
| $lns, ($lns|look_and_say(n-1))
end ;</lang>
end ;</syntaxhighlight>
'''Example'''
'''Example'''
1 | look_and_say(10)
1 | look_and_say(10)
Line 2,589: Line 2,589:
=={{header|Julia}}==
=={{header|Julia}}==
{{Works with|Julia|1.1}}
{{Works with|Julia|1.1}}
<lang julia>function lookandsay(s::String)
<syntaxhighlight lang="julia">function lookandsay(s::String)
rst = IOBuffer()
rst = IOBuffer()
c = 1
c = 1
Line 2,613: Line 2,613:
end
end


println(lookandsayseq(10))</lang>
println(lookandsayseq(10))</syntaxhighlight>


{{out}}
{{out}}
Line 2,619: Line 2,619:


=={{header|K}}==
=={{header|K}}==
<lang k> las: {x{0$,//$(#:'n),'*:'n:(&1,~=':x)_ x:0$'$x}\1}
<syntaxhighlight lang="k"> las: {x{0$,//$(#:'n),'*:'n:(&1,~=':x)_ x:0$'$x}\1}
las 8
las 8
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221</lang>
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun lookAndSay(s: String): String {
fun lookAndSay(s: String): String {
Line 2,648: Line 2,648:
las = lookAndSay(las)
las = lookAndSay(las)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,671: Line 2,671:
=={{header|Lasso}}==
=={{header|Lasso}}==
The Look-and-say sequence is a recursive RLE, so the solution can leverage the same method as used for RLE.
The Look-and-say sequence is a recursive RLE, so the solution can leverage the same method as used for RLE.
<lang Lasso>define rle(str::string)::string => {
<syntaxhighlight lang="lasso">define rle(str::string)::string => {
local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string)
local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string)
while(#orig->size) => {
while(#orig->size) => {
Line 2,698: Line 2,698:
return #str
return #str
}
}
loop(15) => {^ las(1,loop_count) + '\r' ^}</lang>
loop(15) => {^ las(1,loop_count) + '\r' ^}</syntaxhighlight>
{{out}}
{{out}}
<pre>11
<pre>11
Line 2,718: Line 2,718:
=={{header|LiveCode}}==
=={{header|LiveCode}}==
This function takes a string and returns the next Look-And-Say iteration of it:
This function takes a string and returns the next Look-And-Say iteration of it:
<lang Lua>function lookAndSay S
<syntaxhighlight lang="lua">function lookAndSay S
put 0 into C
put 0 into C
put char 1 of S into lastChar
put char 1 of S into lastChar
Line 2,738: Line 2,738:
end repeat
end repeat
put x after message
put x after message
end demoLookAndSay</lang>
end demoLookAndSay</syntaxhighlight>


{{out}}
{{out}}
Line 2,754: Line 2,754:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to look.and.say.loop :in :run :c :out
<syntaxhighlight lang="logo">to look.and.say.loop :in :run :c :out
if empty? :in [output (word :out :run :c)]
if empty? :in [output (word :out :run :c)]
if equal? first :in :c [output look.and.say.loop bf :in :run+1 :c :out]
if equal? first :in :c [output look.and.say.loop bf :in :run+1 :c :out]
Line 2,764: Line 2,764:
end
end


show cascade 10 [print ? look.and.say ?] 1</lang>
show cascade 10 [print ? look.and.say ?] 1</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>--returns an iterator over the first n copies of the look-and-say sequence
<syntaxhighlight lang="lua">--returns an iterator over the first n copies of the look-and-say sequence
function lookandsayseq(n)
function lookandsayseq(n)
local t = {1}
local t = {1}
Line 2,785: Line 2,785:
end
end
end
end
for i in lookandsayseq(10) do print(i) end</lang>
for i in lookandsayseq(10) do print(i) end</syntaxhighlight>


Alternative solution, using LPeg:
Alternative solution, using LPeg:
<lang lua>require "lpeg"
<syntaxhighlight lang="lua">require "lpeg"
local P, C, Cf, Cc = lpeg.P, lpeg.C, lpeg.Cf, lpeg.Cc
local P, C, Cf, Cc = lpeg.P, lpeg.C, lpeg.Cf, lpeg.Cc
lookandsay = Cf(Cc"" * C(P"1"^1 + P"2"^1 + P"3"^1)^1, function (a, b) return a .. #b .. string.sub(b,1,1) end)
lookandsay = Cf(Cc"" * C(P"1"^1 + P"2"^1 + P"3"^1)^1, function (a, b) return a .. #b .. string.sub(b,1,1) end)
Line 2,795: Line 2,795:
print(t)
print(t)
t = lookandsay:match(t)
t = lookandsay:match(t)
end</lang>
end</syntaxhighlight>


Alternative solution, using Lua Pattern:
Alternative solution, using Lua Pattern:
<lang lua>function lookandsay(t)
<syntaxhighlight lang="lua">function lookandsay(t)
return t:gsub("(1*)(2*)(3*)", function (...)
return t:gsub("(1*)(2*)(3*)", function (...)
local ret = {}
local ret = {}
Line 2,816: Line 2,816:
print(t)
print(t)
t = lookandsay(t)
t = lookandsay(t)
end</lang>
end</syntaxhighlight>


<lang lua>function lookandsay2(t)
<syntaxhighlight lang="lua">function lookandsay2(t)
return t:gsub("(1*)(2*)(3*)", function (x, y, z)
return t:gsub("(1*)(2*)(3*)", function (x, y, z)
return (x == "" and x or (#x .. x:sub(1, 1))) ..
return (x == "" and x or (#x .. x:sub(1, 1))) ..
Line 2,830: Line 2,830:
print(t)
print(t)
t = lookandsay2(t)
t = lookandsay2(t)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,847: Line 2,847:
Using regular expressions:
Using regular expressions:
{{trans|Perl}}
{{trans|Perl}}
<lang M4>divert(-1)
<syntaxhighlight lang="m4">divert(-1)
define(`for',
define(`for',
`ifelse($#,0,``$0'',
`ifelse($#,0,``$0'',
Line 2,862: Line 2,862:
`v
`v
define(`v',las(v))')dnl
define(`v',las(v))')dnl
v</lang>
v</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>generate_seq := proc(s)
<syntaxhighlight lang="maple">generate_seq := proc(s)
local times, output, i;
local times, output, i;
times := 1;
times := 1;
Line 2,891: Line 2,891:


#Test:
#Test:
Look_and_Say(10);</lang>
Look_and_Say(10);</syntaxhighlight>


{{out}}
{{out}}
Line 2,910: Line 2,910:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The function:
The function:
<lang Mathematica> LookAndSay[n_Integer?Positive]:= Reverse @@@ Tally /@ Split @ IntegerDigits @ n // Flatten // FromDigits</lang>
<syntaxhighlight lang="mathematica"> LookAndSay[n_Integer?Positive]:= Reverse @@@ Tally /@ Split @ IntegerDigits @ n // Flatten // FromDigits</syntaxhighlight>


takes as input an <em>arbitrary</em> positive integer and generates the next member of the ‘Look and Say’ sequence.
takes as input an <em>arbitrary</em> positive integer and generates the next member of the ‘Look and Say’ sequence.
Line 2,916: Line 2,916:
The first example returns the next 12 numbers of the sequence starting with 1:
The first example returns the next 12 numbers of the sequence starting with 1:


<lang Mathematica>NestList[LookAndSay, 1, 12] // Column</lang>
<syntaxhighlight lang="mathematica">NestList[LookAndSay, 1, 12] // Column</syntaxhighlight>


<pre style='height:15em;overflow:scroll'>1
<pre style='height:15em;overflow:scroll'>1
Line 2,934: Line 2,934:
The second example returns the next 12 numbers of the sequence starting with 7:
The second example returns the next 12 numbers of the sequence starting with 7:


<lang Mathematica>NestList[LookAndSay, 7, 12] // Column</lang>
<syntaxhighlight lang="mathematica">NestList[LookAndSay, 7, 12] // Column</syntaxhighlight>


<pre style='height:15em;overflow:scroll'>7
<pre style='height:15em;overflow:scroll'>7
Line 2,951: Line 2,951:


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>collect(a) := block(
<syntaxhighlight lang="maxima">collect(a) := block(
[n: length(a), b: [ ], x: a[1], m: 1],
[n: length(a), b: [ ], x: a[1], m: 1],
for i from 2 thru n do
for i from 2 thru n do
Line 2,970: Line 2,970:
"1113213211"
"1113213211"
"31131211131221"
"31131211131221"
"13211311123113112211" */</lang>
"13211311123113112211" */</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>fn lookAndSay num =
<syntaxhighlight lang="maxscript">fn lookAndSay num =
(
(
local result = ""
local result = ""
Line 3,002: Line 3,002:
print num
print num
num = lookAndSay num
num = lookAndSay num
)</lang>
)</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
<lang metafont>vardef lookandsay(expr s) =
<syntaxhighlight lang="metafont">vardef lookandsay(expr s) =
string r; r := "";
string r; r := "";
if string s:
if string s:
Line 3,027: Line 3,027:
endfor
endfor


end</lang>
end</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>// Look and Say Sequence
<syntaxhighlight lang="miniscript">// Look and Say Sequence
repeats = function(digit, string)
repeats = function(digit, string)
count = 0
count = 0
Line 3,052: Line 3,052:
print number
print number
numbers = number
numbers = number
end for</lang>
end for</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,069: Line 3,069:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE LookAndSay;
<syntaxhighlight lang="modula2">MODULE LookAndSay;
FROM InOut IMPORT WriteString, WriteLn;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Assign, Length;
FROM Strings IMPORT Assign, Length;
Line 3,109: Line 3,109:
Assign(buf2, buf1);
Assign(buf2, buf1);
END;
END;
END LookAndSay.</lang>
END LookAndSay.</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 3,127: Line 3,127:


=={{header|NewLisp}}==
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
;;; Compute the following number in the sequence
;;; Compute the following number in the sequence
(define (next-number s)
(define (next-number s)
Line 3,149: Line 3,149:
;
;
(go 10)
(go 10)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,166: Line 3,166:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>iterator lookAndSay(n: int): string =
<syntaxhighlight lang="nim">iterator lookAndSay(n: int): string =
var current = "1"
var current = "1"
yield current
yield current
Line 3,184: Line 3,184:


for s in lookAndSay(12):
for s in lookAndSay(12):
echo s</lang>
echo s</syntaxhighlight>


{{out}}
{{out}}
Line 3,202: Line 3,202:
=={{header|Objective-C}}==
=={{header|Objective-C}}==


<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


-(NSString*)lookAndSay:(NSString *)word{
-(NSString*)lookAndSay:(NSString *)word{
Line 3,237: Line 3,237:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
=== Functional ===
=== Functional ===
This function computes a see-and-say sequence from the previous one:
This function computes a see-and-say sequence from the previous one:
<lang ocaml>let rec seeAndSay = function
<syntaxhighlight lang="ocaml">let rec seeAndSay = function
| [], nys -> List.rev nys
| [], nys -> List.rev nys
| x::xs, [] -> seeAndSay(xs, [x; 1])
| x::xs, [] -> seeAndSay(xs, [x; 1])
| x::xs, y::n::nys when x=y -> seeAndSay(xs, y::1+n::nys)
| x::xs, y::n::nys when x=y -> seeAndSay(xs, y::1+n::nys)
| x::xs, nys -> seeAndSay(xs, x::1::nys)</lang>
| x::xs, nys -> seeAndSay(xs, x::1::nys)</syntaxhighlight>
It can be used like this:
It can be used like this:
<lang ocaml>> let gen n =
<syntaxhighlight lang="ocaml">> let gen n =
let xs = Array.create n [1] in
let xs = Array.create n [1] in
for i=1 to n-1 do
for i=1 to n-1 do
Line 3,261: Line 3,261:
[1; 3; 1; 1; 2; 2; 2; 1]; [1; 1; 1; 3; 2; 1; 3; 2; 1; 1];
[1; 3; 1; 1; 2; 2; 2; 1]; [1; 1; 1; 3; 2; 1; 3; 2; 1; 1];
[3; 1; 1; 3; 1; 2; 1; 1; 1; 3; 1; 2; 2; 1];
[3; 1; 1; 3; 1; 2; 1; 1; 1; 3; 1; 2; 2; 1];
[1; 3; 2; 1; 1; 3; 1; 1; 1; 2; 3; 1; 1; 3; 1; 1; 2; 2; 1; 1]|]</lang>
[1; 3; 2; 1; 1; 3; 1; 1; 1; 2; 3; 1; 1; 3; 1; 1; 2; 2; 1; 1]|]</syntaxhighlight>


=== With regular expressions in the Str library ===
=== With regular expressions in the Str library ===
<lang ocaml>#load "str.cma";;
<syntaxhighlight lang="ocaml">#load "str.cma";;


let lookandsay =
let lookandsay =
Line 3,277: Line 3,277:
num := lookandsay !num;
num := lookandsay !num;
print_endline !num;
print_endline !num;
done</lang>
done</syntaxhighlight>


=== With regular expressions in the Pcre library ===
=== With regular expressions in the Pcre library ===
<lang ocaml>open Pcre
<syntaxhighlight lang="ocaml">open Pcre


let lookandsay str =
let lookandsay str =
Line 3,296: Line 3,296:
num := lookandsay !num;
num := lookandsay !num;
print_endline !num;
print_endline !num;
done</lang>
done</syntaxhighlight>


run this example with 'ocaml -I +pcre pcre.cma script.ml'
run this example with 'ocaml -I +pcre pcre.cma script.ml'


=== Imperative ===
=== Imperative ===
<lang ocaml>(* see http://oeis.org/A005150 *)
<syntaxhighlight lang="ocaml">(* see http://oeis.org/A005150 *)


let look_and_say s =
let look_and_say s =
Line 3,342: Line 3,342:
*)
*)


(* see http://oeis.org/A005341 *)</lang>
(* see http://oeis.org/A005341 *)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: mapping
<syntaxhighlight lang="oforth">import: mapping


: lookAndSay ( n -- )
: lookAndSay ( n -- )
[ 1 ] #[ dup .cr group map( [#size, #first] ) expand ] times( n ) ;</lang>
[ 1 ] #[ dup .cr group map( [#size, #first] ) expand ] times( n ) ;</syntaxhighlight>


{{out}} for n = 10 :
{{out}} for n = 10 :
Line 3,366: Line 3,366:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
%% e.g. "21" -> "1211"
%% e.g. "21" -> "1211"
fun {LookAndSayString S}
fun {LookAndSayString S}
Line 3,395: Line 3,395:
end
end
in
in
{ForAll {List.take {LookAndSay 1} 10} Show}</lang>
{ForAll {List.take {LookAndSay 1} 10} Show}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>step(n)={
<syntaxhighlight lang="parigp">step(n)={
my(v=eval(Vec(Str(n))),cur=v[1],ct=1,out="");
my(v=eval(Vec(Str(n))),cur=v[1],ct=1,out="");
v=concat(v,99);
v=concat(v,99);
Line 3,412: Line 3,412:
eval(out)
eval(out)
};
};
n=1;for(i=1,20,print(n);n=step(n))</lang>
n=1;for(i=1,20,print(n);n=step(n))</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 3,418: Line 3,418:
{{works with|Delphi}}
{{works with|Delphi}}
{{libheader|SysUtils}}
{{libheader|SysUtils}}
<lang pascal>program LookAndSayDemo(input, output);
<syntaxhighlight lang="pascal">program LookAndSayDemo(input, output);


{$IFDEF FPC}
{$IFDEF FPC}
Line 3,460: Line 3,460:
number := LookAndSay(number);
number := LookAndSay(number);
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>% ./LookAndSay
<pre>% ./LookAndSay
Line 3,487: Line 3,487:
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
{{libheader|SysUtils}}
{{libheader|SysUtils}}
<lang pascal>
<syntaxhighlight lang="pascal">
program LookAndSayDemo(input, output);
program LookAndSayDemo(input, output);
{$IFDEF FPC}
{$IFDEF FPC}
Line 3,565: Line 3,565:
writeln(i:4,length(number):16,l2/l1:10:6);
writeln(i:4,length(number):16,l2/l1:10:6);
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 3,603: Line 3,603:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub lookandsay {
<syntaxhighlight lang="perl">sub lookandsay {
my $str = shift;
my $str = shift;
$str =~ s/((.)\2*)/length($1) . $2/ge;
$str =~ s/((.)\2*)/length($1) . $2/ge;
Line 3,613: Line 3,613:
print "$num\n";
print "$num\n";
$num = lookandsay($num);
$num = lookandsay($num);
}</lang>
}</syntaxhighlight>


Using string as a cyclic buffer:
Using string as a cyclic buffer:
<lang perl>for (local $_ = "1\n"; s/((.)\2*)//s;) {
<syntaxhighlight lang="perl">for (local $_ = "1\n"; s/((.)\2*)//s;) {
print $1;
print $1;
$_ .= ($1 ne "\n" and length($1)).$2
$_ .= ($1 ne "\n" and length($1)).$2
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">lookandsay</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">lookandsay</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
Line 3,645: Line 3,645:
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,662: Line 3,662:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php


function lookAndSay($str) {
function lookAndSay($str) {
Line 3,680: Line 3,680:
}
}


?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
S1 = "1",
S1 = "1",
foreach(_ in 1..11)
foreach(_ in 1..11)
Line 3,705: Line 3,705:
end
end
end,
end,
V = S ++ C.to_string() ++ [Last].</lang>
V = S ++ C.to_string() ++ [Last].</syntaxhighlight>


{{out}}
{{out}}
Line 3,722: Line 3,722:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de las (Lst)
<syntaxhighlight lang="picolisp">(de las (Lst)
(make
(make
(while Lst
(while Lst
Line 3,728: Line 3,728:
(while (= (setq C (pop 'Lst)) (car Lst))
(while (= (setq C (pop 'Lst)) (car Lst))
(inc 'N) )
(inc 'N) )
(link N C) ) ) ) )</lang>
(link N C) ) ) ) )</syntaxhighlight>
Usage:
Usage:
<lang PicoLisp>: (las (1))
<syntaxhighlight lang="picolisp">: (las (1))
-> (1 1)
-> (1 1)
: (las @)
: (las @)
Line 3,745: Line 3,745:
-> (1 1 1 3 2 1 3 2 1 1)
-> (1 1 1 3 2 1 3 2 1 1)
: (las @)
: (las @)
-> (3 1 1 3 1 2 1 1 1 3 1 2 2 1)</lang>
-> (3 1 1 3 1 2 1 1 1 3 1 2 2 1)</syntaxhighlight>


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang plm>100H:
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 3,800: Line 3,800:
END;
END;
CALL EXIT;
CALL EXIT;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 3,820: Line 3,820:
=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
This uses the <code>RLEncode</code> function from the [[Run-length encoding#PowerBASIC|PowerBASIC Run-length encoding entry]].
This uses the <code>RLEncode</code> function from the [[Run-length encoding#PowerBASIC|PowerBASIC Run-length encoding entry]].
<lang powerbasic>FUNCTION RLEncode (i AS STRING) AS STRING
<syntaxhighlight lang="powerbasic">FUNCTION RLEncode (i AS STRING) AS STRING
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM Loop0 AS LONG, count AS LONG
DIM Loop0 AS LONG, count AS LONG
Line 3,864: Line 3,864:
v = VAL(INPUTBOX$("Enter a number."))
v = VAL(INPUTBOX$("Enter a number."))
MSGBOX lookAndSay(v)
MSGBOX lookAndSay(v)
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function Get-LookAndSay ($n = 1) {
<syntaxhighlight lang="powershell">function Get-LookAndSay ($n = 1) {
$re = [regex] '(.)\1*'
$re = [regex] '(.)\1*'
$ret = ""
$ret = ""
Line 3,887: Line 3,887:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>PS> Get-MultipleLookAndSay 8
<pre>PS> Get-MultipleLookAndSay 8
Line 3,902: Line 3,902:
Works with SWI-Prolog.
Works with SWI-Prolog.


<lang Prolog>look_and_say(L) :-
<syntaxhighlight lang="prolog">look_and_say(L) :-
maplist(write, L), nl,
maplist(write, L), nl,
encode(L, L1),
encode(L, L1),
Line 3,946: Line 3,946:
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
dif(Var,Other).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,964: Line 3,964:


=={{header|Pure}}==
=={{header|Pure}}==
<lang pure>using system;
<syntaxhighlight lang="pure">using system;


// Remove the trailing "L" from the string representation of bigints.
// Remove the trailing "L" from the string representation of bigints.
Line 3,977: Line 3,977:


// This prints the entire sequence, press Ctrl-C to abort.
// This prints the entire sequence, press Ctrl-C to abort.
do (puts.str) (iterate say 1);</lang>
do (puts.str) (iterate say 1);</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
Define i, j, cnt, txt$, curr$, result$
Define i, j, cnt, txt$, curr$, result$
Print("Enter start sequence: "): txt$=Input()
Print("Enter start sequence: "): txt$=Input()
Line 4,005: Line 4,005:
PrintN(#CRLF$+"Press ENTER to exit."): Input()
PrintN(#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


{{out}}
{{out}}
Line 4,024: Line 4,024:
=={{header|Python}}==
=={{header|Python}}==
{{trans|C sharp|C#}}
{{trans|C sharp|C#}}
<lang python>def lookandsay(number):
<syntaxhighlight lang="python">def lookandsay(number):
result = ""
result = ""


Line 4,045: Line 4,045:
for i in range(10):
for i in range(10):
print num
print num
num = lookandsay(num)</lang>
num = lookandsay(num)</syntaxhighlight>


Functional
Functional
{{works with|Python|2.4+}}
{{works with|Python|2.4+}}
<lang python>>>> from itertools import groupby
<syntaxhighlight lang="python">>>> from itertools import groupby
>>> def lookandsay(number):
>>> def lookandsay(number):
return ''.join( str(len(list(g))) + k
return ''.join( str(len(list(g))) + k
Line 4,057: Line 4,057:
>>> for i in range(10):
>>> for i in range(10):
print numberstring
print numberstring
numberstring = lookandsay(numberstring)</lang>
numberstring = lookandsay(numberstring)</syntaxhighlight>


{{out}}
{{out}}
Line 4,072: Line 4,072:


'''As a generator'''<br>
'''As a generator'''<br>
<lang python>>>> from itertools import groupby, islice
<syntaxhighlight lang="python">>>> from itertools import groupby, islice
>>>
>>>
>>> def lookandsay(number='1'):
>>> def lookandsay(number='1'):
Line 4,091: Line 4,091:
1113213211
1113213211
31131211131221
31131211131221
13211311123113112211</lang>
13211311123113112211</syntaxhighlight>


'''Using regular expressions'''<br>
'''Using regular expressions'''<br>
{{trans|Perl}}
{{trans|Perl}}
<lang python>import re
<syntaxhighlight lang="python">import re


def lookandsay(str):
def lookandsay(str):
Line 4,103: Line 4,103:
for i in range(10):
for i in range(10):
print num
print num
num = lookandsay(num)</lang>
num = lookandsay(num)</syntaxhighlight>


=={{header|Q}}==
=={{header|Q}}==
<lang q>las:{{raze string[count@'x],'@'[;0]x:where[differ x]_x}\[x;1#"1"]}
<syntaxhighlight lang="q">las:{{raze string[count@'x],'@'[;0]x:where[differ x]_x}\[x;1#"1"]}
las 8</lang>
las 8</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,123: Line 4,123:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ stack ] is instances
<syntaxhighlight lang="quackery"> [ stack ] is instances


[ 1 instances put
[ 1 instances put
Line 4,143: Line 4,143:
[ dup echo$ cr
[ dup echo$ cr
lookandsay ]
lookandsay ]
echo$ cr</lang>
echo$ cr</syntaxhighlight>


{{out}}
{{out}}
Line 4,168: Line 4,168:
Returning the value as an integer limits how long the sequence can get,
Returning the value as an integer limits how long the sequence can get,
so the option for integer or character return values are provided.
so the option for integer or character return values are provided.
<lang R>look.and.say <- function(x, return.an.int=FALSE)
<syntaxhighlight lang="r">look.and.say <- function(x, return.an.int=FALSE)
{
{
#convert number to character vector
#convert number to character vector
Line 4,182: Line 4,182:
#convert to number, if desired
#convert to number, if desired
if(return.an.int) as.integer(newstr) else newstr
if(return.an.int) as.integer(newstr) else newstr
}</lang>
}</syntaxhighlight>
Example usage:
Example usage:
<lang R>x <- 1
<syntaxhighlight lang="r">x <- 1
for(i in 1:10)
for(i in 1:10)
{
{
x <- look.and.say(x)
x <- look.and.say(x)
print(x)
print(x)
}</lang>
}</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 4,203: Line 4,203:


(for-each displayln (look-and-say-sequence 10))
(for-each displayln (look-and-say-sequence 10))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,225: Line 4,225:
In Raku it is natural to avoid explicit loops; rather we use the sequence operator to define a lazy infinite sequence. We'll print the first 15 values here.
In Raku it is natural to avoid explicit loops; rather we use the sequence operator to define a lazy infinite sequence. We'll print the first 15 values here.


<lang perl6>.say for ('1', *.subst(/(.)$0*/, { .chars ~ .[0] }, :g) ... *)[^15];</lang>
<syntaxhighlight lang="raku" line>.say for ('1', *.subst(/(.)$0*/, { .chars ~ .[0] }, :g) ... *)[^15];</syntaxhighlight>


{{out}}
{{out}}
Line 4,251: Line 4,251:


===simple version===
===simple version===
<lang rexx>/*REXX program displays the sequence (and/or lengths) for the look and say series.*/
<syntaxhighlight lang="rexx">/*REXX program displays the sequence (and/or lengths) for the look and say series.*/
parse arg N ! . /*obtain optional arguments from the CL*/
parse arg N ! . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 4,272: Line 4,272:
$= $ || _ || y /*build the "look and say" sequence. */
$= $ || _ || y /*build the "look and say" sequence. */
k= k + _ /*now, point to the next character. */
k= k + _ /*now, point to the next character. */
end /*k*/</lang>
end /*k*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input values of: &nbsp; &nbsp; <tt> 20 &nbsp; 1 </tt>}}
{{out|output|text=&nbsp; when using the default input values of: &nbsp; &nbsp; <tt> 20 &nbsp; 1 </tt>}}
<pre>
<pre>
Line 4,386: Line 4,386:
<br>it appends the sequence generated (so far) to the primary sequence, and starts with a null sequence.
<br>it appends the sequence generated (so far) to the primary sequence, and starts with a null sequence.
<br>This avoids appending a small character string to a growing larger and larger character string.
<br>This avoids appending a small character string to a growing larger and larger character string.
<lang rexx>/*REXX program displays the sequence (and/or lengths) for the look and say series.*/
<syntaxhighlight lang="rexx">/*REXX program displays the sequence (and/or lengths) for the look and say series.*/
parse arg N ! . /*obtain optional arguments from the CL*/
parse arg N ! . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 4,413: Line 4,413:
chSize= chSize + 100 /*bump the chunkSize (length) counter.*/
chSize= chSize + 100 /*bump the chunkSize (length) counter.*/
end /*k*/
end /*k*/
return ! || $ /*return the ! string plus the $ string*/</lang>
return ! || $ /*return the ! string plus the $ string*/</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version &nbsp; (the simple version).}}<br><br>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version &nbsp; (the simple version).}}<br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
number = "1"
number = "1"
for nr = 1 to 10
for nr = 1 to 10
Line 4,437: Line 4,437:
end
end
return o
return o
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
The simplest one:
The simplest one:
<lang ruby>
<syntaxhighlight lang="ruby">
class String
class String
def look_and_say
def look_and_say
Line 4,450: Line 4,450:
ss = '1'
ss = '1'
12.times {puts ss; ss = ss.look_and_say}
12.times {puts ss; ss = ss.look_and_say}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,468: Line 4,468:


{{trans|Perl}}
{{trans|Perl}}
<lang ruby>def lookandsay(str)
<syntaxhighlight lang="ruby">def lookandsay(str)
str.gsub(/(.)\1*/) {$&.length.to_s + $1}
str.gsub(/(.)\1*/) {$&.length.to_s + $1}
end
end
Line 4,476: Line 4,476:
puts num
puts num
num = lookandsay(num)
num = lookandsay(num)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,492: Line 4,492:


Using Enumerable#chunk
Using Enumerable#chunk
<lang ruby>def lookandsay(str)
<syntaxhighlight lang="ruby">def lookandsay(str)
str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join
str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join
end
end
Line 4,499: Line 4,499:
9.times do
9.times do
puts num = lookandsay(num)
puts num = lookandsay(num)
end</lang>
end</syntaxhighlight>
The '''output''' is the same above.
The '''output''' is the same above.


Without regular expression:
Without regular expression:


<lang ruby># Adding clusterization (http://apidock.com/rails/Enumerable/group_by)
<syntaxhighlight lang="ruby"># Adding clusterization (http://apidock.com/rails/Enumerable/group_by)
module Enumerable
module Enumerable
# clumps adjacent elements together
# clumps adjacent elements together
Line 4,520: Line 4,520:
cluster
cluster
end
end
end</lang>
end</syntaxhighlight>


Using Array#cluster defined above:
Using Array#cluster defined above:


<lang ruby>def print_sequence(input_sequence, seq=10)
<syntaxhighlight lang="ruby">def print_sequence(input_sequence, seq=10)
return unless seq > 0
return unless seq > 0
puts input_sequence.join
puts input_sequence.join
Line 4,533: Line 4,533:
end
end


print_sequence([1])</lang>
print_sequence([1])</syntaxhighlight>
The '''output''' is the same above.
The '''output''' is the same above.


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn next_sequence(in_seq: &[i8]) -> Vec<i8> {
<syntaxhighlight lang="rust">fn next_sequence(in_seq: &[i8]) -> Vec<i8> {
assert!(!in_seq.is_empty());
assert!(!in_seq.is_empty());


Line 4,566: Line 4,566:
seq = next_sequence(&seq);
seq = next_sequence(&seq);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Sequence 0: [1]
<pre>Sequence 0: [1]
Line 4,580: Line 4,580:


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
look_and_say!: STR is
look_and_say!: STR is
current ::= "1";
current ::= "1";
Line 4,606: Line 4,606:
end;
end;
end;
end;
end;</lang>
end;</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 4,624: Line 4,624:


===Recursive===
===Recursive===
<lang Scala>import scala.annotation.tailrec
<syntaxhighlight lang="scala">import scala.annotation.tailrec


object LookAndSay extends App {
object LookAndSay extends App {
Line 4,650: Line 4,650:
}
}


}</lang>
}</syntaxhighlight>
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/V5Jn5mf/0 (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/7kn0fV3gTaqCDLIv4QGuMQ Scastie (JVM)].
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/V5Jn5mf/0 (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/7kn0fV3gTaqCDLIv4QGuMQ Scastie (JVM)].
===using Iterator===
===using Iterator===
{{libheader|Scala}}<lang scala>def lookAndSay(seed: BigInt) = {
{{libheader|Scala}}<syntaxhighlight lang="scala">def lookAndSay(seed: BigInt) = {
val s = seed.toString
val s = seed.toString
( 1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
( 1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
Line 4,663: Line 4,663:
}
}


def lookAndSayIterator(seed: BigInt) = Iterator.iterate(seed)(lookAndSay)</lang>
def lookAndSayIterator(seed: BigInt) = Iterator.iterate(seed)(lookAndSay)</syntaxhighlight>


===using Stream===
===using Stream===
<lang Scala>object Main extends App {
<syntaxhighlight lang="scala">object Main extends App {


def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = {
def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = {
Line 4,682: Line 4,682:


(lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString("")))
(lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString("")))
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func string: lookAndSay (in integer: level, in string: stri) is func
const func string: lookAndSay (in integer: level, in string: stri) is func
Line 4,712: Line 4,712:
writeln(lookAndSay(level, "1"));
writeln(lookAndSay(level, "1"));
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,734: Line 4,734:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>func lookandsay(str) {
<syntaxhighlight lang="ruby">func lookandsay(str) {
str.gsub(/((.)\2*)/, {|a,b| a.len.to_s + b });
str.gsub(/((.)\2*)/, {|a,b| a.len.to_s + b });
}
}
Line 4,742: Line 4,742:
say num;
say num;
num = lookandsay(num);
num = lookandsay(num);
} * 10;</lang>
} * 10;</syntaxhighlight>


{{out}}
{{out}}
Line 4,758: Line 4,758:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>String extend [
<syntaxhighlight lang="smalltalk">String extend [
lookAndSay [ |anElement nextElement counter coll newColl|
lookAndSay [ |anElement nextElement counter coll newColl|
coll := (self asOrderedCollection).
coll := (self asOrderedCollection).
Line 4,787: Line 4,787:
r displayNl.
r displayNl.
r := r lookAndSay.
r := r lookAndSay.
]</lang>
]</syntaxhighlight>


{{works with|Pharo}}
{{works with|Pharo}}
<lang smalltalk>String compile:
<syntaxhighlight lang="smalltalk">String compile:
'lookAndSay |anElement nextElement counter coll newColl|
'lookAndSay |anElement nextElement counter coll newColl|
coll := (self asOrderedCollection).
coll := (self asOrderedCollection).
Line 4,820: Line 4,820:
]).
]).
result.
result.
</syntaxhighlight>
</lang>


Output:
Output:
Line 4,833: Line 4,833:
This is by far the easiest solution.
This is by far the easiest solution.


<lang SNOBOL4>* # Encode RLE
<syntaxhighlight lang="snobol4">* # Encode RLE
define('rle(str)c,n') :(rle_end)
define('rle(str)c,n') :(rle_end)
rle str len(1) . c :f(return)
rle str len(1) . c :f(return)
Line 4,848: Line 4,848:
* Test and display
* Test and display
looksay(1,10)
looksay(1,10)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 4,863: Line 4,863:


=={{header|SQL}}==
=={{header|SQL}}==
<lang sql>DROP VIEW delta;
<syntaxhighlight lang="sql">DROP VIEW delta;
CREATE VIEW delta AS
CREATE VIEW delta AS
SELECT sequence1.v AS x,
SELECT sequence1.v AS x,
Line 4,909: Line 4,909:
DELETE FROM sequence;
DELETE FROM sequence;
INSERT INTO sequence VALUES(-1,0);
INSERT INTO sequence VALUES(-1,0);
INSERT INTO sequence SELECT * FROM rle;</lang>
INSERT INTO sequence SELECT * FROM rle;</syntaxhighlight>


Usage:
Usage:
Line 4,952: Line 4,952:
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<lang sql pl>
<syntaxhighlight lang="sql pl">
SET SERVEROUTPUT ON @
SET SERVEROUTPUT ON @


Line 4,993: Line 4,993:
END WHILE;
END WHILE;
END @
END @
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,015: Line 5,015:
=={{header|Swift}}==
=={{header|Swift}}==
{{trans|Rust}}
{{trans|Rust}}
<lang swift>func lookAndSay(_ seq: [Int]) -> [Int] {
<syntaxhighlight lang="swift">func lookAndSay(_ seq: [Int]) -> [Int] {
var result = [Int]()
var result = [Int]()
var cur = seq[0]
var cur = seq[0]
Line 5,042: Line 5,042:
print("Seq \(i): \(seq)")
print("Seq \(i): \(seq)")
seq = lookAndSay(seq)
seq = lookAndSay(seq)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,058: Line 5,058:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc lookandsay n {
<syntaxhighlight lang="tcl">proc lookandsay n {
set new ""
set new ""
while {[string length $n] > 0} {
while {[string length $n] > 0} {
Line 5,075: Line 5,075:
puts [next_lookandsay] ;# ==> 1211
puts [next_lookandsay] ;# ==> 1211
puts [next_lookandsay] ;# ==> 111221
puts [next_lookandsay] ;# ==> 111221
puts [next_lookandsay] ;# ==> 312211</lang>
puts [next_lookandsay] ;# ==> 312211</syntaxhighlight>


Alternatively, with coroutines:
Alternatively, with coroutines:
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>proc seq_lookandsay {n {coroName next_lookandsay}} {
<syntaxhighlight lang="tcl">proc seq_lookandsay {n {coroName next_lookandsay}} {
coroutine $coroName apply {n {
coroutine $coroName apply {n {
for {} {[yield $n] ne "stop"} {set n $new} {
for {} {[yield $n] ne "stop"} {set n $new} {
Line 5,099: Line 5,099:
puts [next_lookandsay]
puts [next_lookandsay]
puts [next_lookandsay]
puts [next_lookandsay]
puts [next_lookandsay]</lang>
puts [next_lookandsay]</syntaxhighlight>


{{out}}
{{out}}
Line 5,116: Line 5,116:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
$$ MODE TUSCRIPT,{}
num=1,say=""
num=1,say=""
Line 5,129: Line 5,129:
IF (look==14) EXIT
IF (look==14) EXIT
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style='height:30ex;overflow:scroll'>
<pre style='height:30ex;overflow:scroll'>
Line 5,150: Line 5,150:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash}}
{{works with|bash}}
<lang bash>lookandsay() {
<syntaxhighlight lang="bash">lookandsay() {
local num=$1 char seq i
local num=$1 char seq i
for ((i=0; i<=${#num}; i++)); do
for ((i=0; i<=${#num}; i++)); do
Line 5,166: Line 5,166:
echo $num
echo $num
num=$( lookandsay $num )
num=$( lookandsay $num )
done</lang>
done</syntaxhighlight>


{{out}}
{{out}}
Line 5,183: Line 5,183:
The look_and_say function returns the first n results
The look_and_say function returns the first n results
by iterating the function that maps a given sequence to its successor.
by iterating the function that maps a given sequence to its successor.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 5,190: Line 5,190:
#show+
#show+


main = look_and_say 10</lang>
main = look_and_say 10</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 5,204: Line 5,204:


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vba">
<lang VBA>
Public Sub LookAndSay(Optional Niter As Integer = 10)
Public Sub LookAndSay(Optional Niter As Integer = 10)
'generate "Niter" members of the look-and-say sequence
'generate "Niter" members of the look-and-say sequence
Line 5,254: Line 5,254:
End If
End If
End Sub
End Sub
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,272: Line 5,272:
=={{header|VBScript}}==
=={{header|VBScript}}==
=====Implementation=====
=====Implementation=====
<lang vb>function looksay( n )
<syntaxhighlight lang="vb">function looksay( n )
dim i
dim i
dim accum
dim accum
Line 5,291: Line 5,291:
loop
loop
looksay = res
looksay = res
end function</lang>
end function</syntaxhighlight>


=====Invocation=====
=====Invocation=====
<lang vb>dim m
<syntaxhighlight lang="vb">dim m
m = 1
m = 1
for i = 0 to 13
for i = 0 to 13
m = looksay(m)
m = looksay(m)
wscript.echo m
wscript.echo m
next</lang>
next</syntaxhighlight>


{{out}}
{{out}}
Line 5,325: Line 5,325:
10 sequences are created in this example.
10 sequences are created in this example.


<lang vedit>Repeat(10) {
<syntaxhighlight lang="vedit">Repeat(10) {
BOL
BOL
Reg_Empty(20)
Reg_Empty(20)
Line 5,334: Line 5,334:
}
}
Ins_Newline Reg_Ins(20)
Ins_Newline Reg_Ins(20)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,351: Line 5,351:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>fn lss(s string) string {
<syntaxhighlight lang="vlang">fn lss(s string) string {
mut r := ''
mut r := ''
mut c := s[0..1]
mut c := s[0..1]
Line 5,375: Line 5,375:
println(s)
println(s)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,392: Line 5,392:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>var lookAndSay = Fn.new { |s|
<syntaxhighlight lang="ecmascript">var lookAndSay = Fn.new { |s|
var res = ""
var res = ""
var digit = s[0]
var digit = s[0]
Line 5,412: Line 5,412:
System.print(las)
System.print(las)
las = lookAndSay.call(las)
las = lookAndSay.call(las)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,434: Line 5,434:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
dim X$(2)
dim X$(2)
i = 0 // índice de cadena de entrada
i = 0 // índice de cadena de entrada
Line 5,459: Line 5,459:
next n
next n
print
print
</syntaxhighlight>
</lang>
{{out}}La salida es similar a la de [[#FreeBASIC|FreeBASIC]], mostrada arriba.
{{out}}La salida es similar a la de [[#FreeBASIC|FreeBASIC]], mostrada arriba.


=={{header|Yorick}}==
=={{header|Yorick}}==


<lang yorick>func looksay(input) {
<syntaxhighlight lang="yorick">func looksay(input) {
// Special case: one digit
// Special case: one digit
if(strlen(input) == 1)
if(strlen(input) == 1)
Line 5,493: Line 5,493:
write, val;
write, val;
val = looksay(val);
val = looksay(val);
} while(strlen(val) < 80);</lang>
} while(strlen(val) < 80);</syntaxhighlight>


{{out}}
{{out}}
Line 5,515: Line 5,515:
Treating the task as a string manipulation problem.
Treating the task as a string manipulation problem.
{{trans|Scala}}
{{trans|Scala}}
<lang zkl>fcn lookAndSay(seed){ // numeric String --> numeric String
<syntaxhighlight lang="zkl">fcn lookAndSay(seed){ // numeric String --> numeric String
len,c:=[1..seed.len()-1].reduce(fcn([(len,c)]lc,index,s,sb){
len,c:=[1..seed.len()-1].reduce(fcn([(len,c)]lc,index,s,sb){
if(c!=s[index]) { sb.write(len); sb.write(c); lc.clear(1,s[index]) }
if(c!=s[index]) { sb.write(len); sb.write(c); lc.clear(1,s[index]) }
Line 5,522: Line 5,522:
sb.write(len); sb.write(c);
sb.write(len); sb.write(c);
sb.close();
sb.close();
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}