Look-and-say sequence: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Picat}}: Added {{out}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 42:
{{trans|Python}}
<
V result = ‘’
V repeat = number[0]
Line 61:
L 10
print(num)
num = lookandsay(num)</
{{out}}
Line 80:
<
puts: equ 9
Line 163:
; Due to how CP/M loads programs, the memory after here
; is free until we hit the stack.
</syntaxhighlight>
=={{header|8086 Assembly}}==
<
cpu 8086
puts: equ 9h ; MS/DOS system call to print a string
Line 220:
section .data
newline: db 13,10,'$' ; Newline to print in between members
memb: db '1$' ; This is where the current member is stored</
=={{header|Action!}}==
<
CHAR c
BYTE len
Line 288:
FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Look-and-say_sequence.png Screenshot from Atari 8-bit computer]
Line 307:
=={{header|Ada}}==
<
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
Line 319:
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";</
This function can be used as follows:
<
Put_Line (+(+"1"));
Put_Line (+(+(+"1")));
Line 330:
Put_Line (+(+(+(+(+(+(+(+"1"))))))));
Put_Line (+(+(+(+(+(+(+(+(+"1")))))))));
Put_Line (+(+(+(+(+(+(+(+(+(+"1"))))))))));</
{{out}}
<pre>
Line 350:
{{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}}
<
BEGIN
CHAR item = s[LWB s];
Line 376:
print ((+(+(+(+(+(+(+(+"1"))))))), new line));
print ((+(+(+(+(+(+(+(+(+"1")))))))), new line));
print ((+(+(+(+(+(+(+(+(+(+"1"))))))))), new line))</
{{out}}
<pre>
Line 392:
=={{header|ALGOL-M}}==
<
string(1) function digit(n);
integer n;
Line 430:
curlen := j - 1;
end;
end</
{{out}}
<pre>1
Line 449:
=={{header|APL}}==
<
⎕IO←0
d←{(1↓⍵)-¯1↓⍵}
f←{m←(0≠d ⍵),1 ⋄ ,(d ¯1,m/⍳⍴⍵),[.5](m/⍵)}
{(f⍣⍵) ,1}¨⍳10
</syntaxhighlight>
This is an ugly little APL2 function that accepts a numeric vector (or scalar) and returns the result.
Apologies for the labeled loop...
<
R←LNS V;T
R←0⍴0 ⍝ initiate empty reply
Line 465:
R←R,T,↑V ⍝ append t and the 1st digit
→(0≠↑⍴V←T↓V)/LOOP ⍝ drop t digits and iterate
</syntaxhighlight>
=={{header|AppleScript}}==
<
if (howMany < 1) then return {}
Line 515:
-- Test code:
return lookAndSay(1, 10)</
{{output}}
<
=={{header|Arturo}}==
<
if n=0 -> return "1"
previous: lookAndSay n-1
Line 545:
loop 0..10 'x [
print [x "->" lookAndSay x]
]</
{{out}}
Line 562:
=={{header|AutoHotkey}}==
<
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Line 598:
}
Return, r c d
}</
=={{header|AWK}}==
<
{
s = ""
Line 627:
print b
}
}</
=={{header|BASIC}}==
<
20 FOR Z=1 TO 15
30 PRINT I$
Line 641:
100 NEXT I
110 I$=O$
120 NEXT Z</
{{out}}
<pre>1
Line 660:
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
# look and say
Line 686:
print a$[j]
next n
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
FOR i% = 1 TO 10
number$ = FNlooksay(number$)
Line 708:
i% = j%
UNTIL i% > LEN(n$)
= o$</
{{out}}
<pre>
Line 724:
=={{header|BCPL}}==
<
manifest $(
Line 774:
move(buf1,buf2)
$)
$)</
{{out}}
<pre>1
Line 793:
=={{header|BQN}}==
<
>((⌈´≠¨)↑¨⊢) LookSay⍟(↕15)"1"</
{{out}}
<pre>┌─
Line 817:
=={{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.
<
& 0:?lines
& whl
Line 839:
)
)
);</
{{out}}
<pre>11
Line 854:
=={{header|C}}==
This program will not stop until killed or running out of memory.
<
#include <stdlib.h>
Line 875:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Text;
using System.Linq;
Line 917:
}
}
}</
{{out}}
Line 932:
Alternate version using Regex (C#2 syntax only):
<
using System;
using System.Text.RegularExpressions;
Line 972:
}
}
}</
{{out}} (with args: 1 15):
<pre>1
Line 991:
=={{header|C++}}==
<
#include <sstream>
#include <string>
Line 1,020:
std::cout << laf << '\n';
}
}</
=={{header|Ceylon}}==
<
function lookAndSay(Integer|String input) {
Line 1,050:
print(result);
}
}</
=={{header|Clojure}}==
No ugly int-to-string-and-back conversions.
<
"Returns a seq of the digits of a number (L->R)."
[n]
Line 1,070:
(defn look-and-say [n]
(->> n digits-seq (partition-by identity)
(mapcat (juxt count first)) join-digits))</
{{out}}
<
(1 11 21 1211 111221 312211 13112221 1113213211)</
=={{header|CLU}}==
<
out: array[char] := array[char]$[]
count: int := 0
Line 1,109:
cur := look_and_say(cur)
end
end start_up</
{{out}}
<pre>1
Line 1,128:
=={{header|COBOL}}==
<
PROGRAM-ID. LOOK-AND-SAY-SEQ.
Line 1,170:
SUBTRACT 1 FROM STEP-AMOUNT.
IF STEP-AMOUNT IS NOT EQUAL TO ZERO GO TO LOOK-AND-SAY.
STOP RUN.</
{{out}}
<pre>1
Line 1,188:
=={{header|Common Lisp}}==
<
"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
Line 1,206:
(parse-integer (string (cdr pair)))))
(compress (princ-to-string number))
:initial-value 0))</
Example use:
<
Straight character counting:
<
(let ((out (list (char s 0) 0)))
(loop for x across s do
Line 1,223:
(loop for s = "1" then (look-and-say s)
repeat 10
do (write-line s))</
=={{header|Cowgol}}==
<
include "strings.coh";
Line 1,270:
CopyString(&nextbuf as [uint8], &curbuf as [uint8]);
members := members - 1;
end loop;</
{{out}}
Line 1,294:
{{trans|Ruby}}
The simplest one:
<
def lookandsay
gsub(/(.)\1*/){ |s| s.size.to_s + s[0] }
Line 1,301:
ss = '1'
12.times { puts ss; ss = ss.to_s.lookandsay }</
{{trans|Ruby from Perl}}
<
str.gsub(/(.)\1*/) { |s| s.size.to_s + $1 }
end
num = "1"
12.times { puts num; num = lookandsay(num) }</
{{trans|Ruby}}
Using Enumerable#chunks
<
str.chars.chunks(&.itself).map{ |(c, x)| x.size.to_s + c }.join
end
num = "1"
12.times { puts num; num = lookandsay(num) }</
{{out}}
Line 1,337:
=={{header|D}}==
===Short Functional Version===
<
enum say = (in string s) pure => s.group.map!q{ text(a[1],a[0]) }.join;
Line 1,343:
void main() {
"1".recurrence!((t, n) => t[n - 1].say).take(8).writeln;
}</
{{out}}
<pre>["1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211"]</pre>
===Beginner Imperative Version===
<
pure string lookAndSay(string s){
Line 1,364:
for(auto i=0; i<10; i++)
(s = s.lookAndSay).writeln;
}</
{{out}}
<pre>11
Line 1,378:
===Fast Imperative Version===
<
void showLookAndSay(bool showArrays)(in uint n) nothrow {
Line 1,471:
immutable n = (args.length == 2) ? args[1].to!uint : 10;
n.showLookAndSay!true;
}</
{{out}}
<pre>Allocated 116 bytes.
Line 1,488:
With:
<syntaxhighlight lang
{{out}}
<pre>Allocated 158045069 bytes.
Line 1,514:
===Intermediate Version===
This mostly imperative version is intermediate in both speed and code size:
<
import std.stdio, std.conv, std.algorithm, std.array, std.string;
Line 1,532:
writefln("%2d: n. digits: %d", i, seq.length);
}
}</
The output is the same as the second version.
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).
<
// On Windows this uses the printf from the Microsoft C runtime,
Line 1,685:
evolve(39, n - base);
'\n'.putchar;
}</
=={{header|Delphi}}==
Line 1,691:
=={{header|Draco}}==
<
proc nonrec look_and_say(*char inp, outp) void:
Line 1,722:
CharsCopy(&buf1[0], &buf2[0])
od
corp</
{{out}}
<pre>1
Line 1,740:
=={{header|E}}==
<
var seen := null
var count := 0
Line 1,765:
println(number)
number := lookAndSayNext(number)
}</
=={{header|EchoLisp}}==
<
(lib 'math) ;; for (number->list) = explode function
(lib 'list) ;; (group)
Line 1,782:
(next L)))
</syntaxhighlight>
{{out}}
<
(task 10 1)
1
Line 1,796:
31131211131221
13211311123113112211
</syntaxhighlight>
=={{header|Elixir}}==
<
def next(n) do
Enum.chunk_by(to_char_list(n), &(&1))
Line 1,821:
end
LookAndSay.main(System.argv)</
{{out}}
Line 1,827:
'''Regex version:'''
<
def look_and_say(n) do
Regex.replace(~r/(.)\1*/, to_string(n), fn x,y -> [to_string(String.length(x)),y] end)
Line 1,834:
end
IO.inspect Enum.reduce(1..9, [1], fn _,acc -> [RC.look_and_say(hd(acc)) | acc] end) |> Enum.reverse</
{{out}}
Line 1,843:
=={{header|Erlang}}==
<
-export([look_and_say/1, look_and_say/2]).
Line 1,860:
look_and_say(T, H, N+1, Acc);
look_and_say([H|T], Current, N, Acc) ->
look_and_say(T, H, 1, [Current, $0+N | Acc]).</
{{out}}
Line 1,876:
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM LOOK
Line 1,901:
END FOR
END PROGRAM
</syntaxhighlight>
<pre>
11
Line 1,917:
=={{header|F Sharp|F#}}==
Library functions somehow missing in F# out of the box (but present in haskell)
<
let rec brk p lst =
match lst with
Line 1,938:
let group lst : list<list<'a>> when 'a : equality = groupBy (=) lst
</syntaxhighlight>
Implementation
<
let lookAndSay =
let describe (xs: char list) =
Line 1,952:
Seq.take 10 lookAndSay
</syntaxhighlight>
=={{header|Factor}}==
<
unclip-slice swap [ 1 ] 2dip [
2dup = [ drop [ 1 + ] dip ] [
Line 1,964:
: look-and-say ( str -- str' ) [ (look-and-say) ] "" make ;
"1" 10 [ dup print look-and-say ] times print</
=={{header|Fennel}}==
<
(let [lst t
ret []]
Line 1,983:
(for [i 1 10]
(print (table.concat lst))
(set lst (look-and-say lst)))</
Alternative solution
<
(var ret [])
(var (num cnt) (values (s:sub 1 1) 1))
Line 2,002:
(for [i 1 10]
(print str)
(set str (look-and-say str)))</
=={{header|FOCAL}}==
<
01.20 S B(0)=1;S B(1)=0
01.30 F Z=1,M;D 4;D 2
Line 2,037:
04.40 D 3
04.50 S X=X+1
04.60 G 4.2</
{{out}}
<pre>HOW MANY:12
Line 2,054:
=={{header|Forth}}==
<
create buf2 256 allot
buf1 value src
Line 2,081:
0 do next-look-and-say cr src count type loop ;
10 look-and-say</
=={{header|Fortran}}==
<
implicit none
Line 2,114:
end subroutine look_and_say
end module LookAndSay</
<
use LookAndSay
implicit none
Line 2,132:
end do
end program LookAndSayTest</
=={{header|FreeBASIC}}==
{{trans|BASIC256}}
<
Dim As Integer n, j, k, k0, r
Dim As String X(2)
Line 2,162:
Next n
End
</syntaxhighlight>
{{out}}
<pre>
Line 2,181:
=={{header|Frink}}==
<
LookAndSay = "12211123"
println["Starting Value: " + LookAndSay]
Line 2,206:
println["$i - $LookAndSay"]
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,226:
'''[https://gambas-playground.proko.eu/?gist=83d63e1706fa1dc3c7468b1e9d7bcf05 Click this link to run this code]'''
<
Dim i, j, cnt As Integer
Dim txt$, curr$, result$ As String
Line 2,250:
Dec i
Until i <= 0
End</
Output:
<pre>
Line 2,257:
=={{header|GAP}}==
<
local c, r, cur, ncur, v;
v := "123";
Line 2,293:
LookAndSay(last); # "1321132132111213122112311311222113111221131221"
LookAndSay(last); # "11131221131211131231121113112221121321132132211331222113112211"
LookAndSay(last); # "311311222113111231131112132112311321322112111312211312111322212311322113212221"</
=={{header|Go}}==
<
import (
Line 2,326:
fmt.Println(s)
}
}</
{{out}}
<pre>
Line 2,341:
=={{header|Groovy}}==
<
def encoded = new StringBuilder()
(sequence.toString() =~ /(([0-9])\2*)/).each { matcher ->
Line 2,347:
}
encoded.toString()
}</
Test Code
<
(1..12).each {
println sequence
sequence = lookAndSay(sequence)
}</
{{out}}
<pre>1
Line 2,369:
=={{header|Haskell}}==
<
import Data.List (group)
Line 2,393:
where describe run = show (length run) ++ take 1 run
main = mapM_ print (iterate lookAndSay 1) -- display sequence until interrupted</
=={{header|Haxe}}==
<
class Main
Line 2,434:
return results;
}
}</
=={{header|Icon}} and {{header|Unicon}}==
<
every 1 to 10 do
write(n := nextlooknsayseq(\n | 1))
Line 2,450:
}
return n2
end</
{{out}}
Line 2,467:
'''Solution''':
<
'''Example''':
<
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221</
Note the result is an actual numeric sequence (cf. the textual solutions given in other languages).
Line 2,478:
{{trans|C#}}
{{works with|Java|1.5+}}
<
StringBuilder result= new StringBuilder();
Line 2,495:
}
return result.toString();
}</
Testing:
<
String num = "1";
Line 2,504:
num = lookandsay(num);
}
}</
{{out}}
<pre>1
Line 2,520:
=== With RegExp ===
{{trans|Perl}}
<
return str.replace(/(.)\1*/g, function(seq, p1){return seq.length.toString() + p1})
}
Line 2,528:
alert(num);
num = lookandsay(num);
}</
=== Imperative version ===
<
var tokens=[]
var i=0, j=1
Line 2,543:
var phrase="1"
for(var n=0; n<10; n++ )
console.log( phrase = lookAndSay( phrase ) )</
{{Output}}
<pre>11
Line 2,558:
=={{header|jq}}==
{{Works with|jq|1.4}}
<
def head(c; n): if .[n:n+1] == c then head(c; n+1) else n end;
tostring
Line 2,572:
else look_and_say as $lns
| $lns, ($lns|look_and_say(n-1))
end ;</
'''Example'''
1 | look_and_say(10)
Line 2,589:
=={{header|Julia}}==
{{Works with|Julia|1.1}}
<
rst = IOBuffer()
c = 1
Line 2,613:
end
println(lookandsayseq(10))</
{{out}}
Line 2,619:
=={{header|K}}==
<
las 8
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221</
=={{header|Kotlin}}==
<
fun lookAndSay(s: String): String {
Line 2,648:
las = lookAndSay(las)
}
}</
{{out}}
Line 2,671:
=={{header|Lasso}}==
The Look-and-say sequence is a recursive RLE, so the solution can leverage the same method as used for RLE.
<
local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string)
while(#orig->size) => {
Line 2,698:
return #str
}
loop(15) => {^ las(1,loop_count) + '\r' ^}</
{{out}}
<pre>11
Line 2,718:
=={{header|LiveCode}}==
This function takes a string and returns the next Look-And-Say iteration of it:
<
put 0 into C
put char 1 of S into lastChar
Line 2,738:
end repeat
put x after message
end demoLookAndSay</
{{out}}
Line 2,754:
=={{header|Logo}}==
<
if empty? :in [output (word :out :run :c)]
if equal? first :in :c [output look.and.say.loop bf :in :run+1 :c :out]
Line 2,764:
end
show cascade 10 [print ? look.and.say ?] 1</
=={{header|Lua}}==
<
function lookandsayseq(n)
local t = {1}
Line 2,785:
end
end
for i in lookandsayseq(10) do print(i) end</
Alternative solution, using LPeg:
<
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)
Line 2,795:
print(t)
t = lookandsay:match(t)
end</
Alternative solution, using Lua Pattern:
<
return t:gsub("(1*)(2*)(3*)", function (...)
local ret = {}
Line 2,816:
print(t)
t = lookandsay(t)
end</
<
return t:gsub("(1*)(2*)(3*)", function (x, y, z)
return (x == "" and x or (#x .. x:sub(1, 1))) ..
Line 2,830:
print(t)
t = lookandsay2(t)
end</
{{out}}
Line 2,847:
Using regular expressions:
{{trans|Perl}}
<
define(`for',
`ifelse($#,0,``$0'',
Line 2,862:
`v
define(`v',las(v))')dnl
v</
=={{header|Maple}}==
<
local times, output, i;
times := 1;
Line 2,891:
#Test:
Look_and_Say(10);</
{{out}}
Line 2,910:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The function:
<
takes as input an <em>arbitrary</em> positive integer and generates the next member of the ‘Look and Say’ sequence.
Line 2,916:
The first example returns the next 12 numbers of the sequence starting with 1:
<
<pre style='height:15em;overflow:scroll'>1
Line 2,934:
The second example returns the next 12 numbers of the sequence starting with 7:
<
<pre style='height:15em;overflow:scroll'>7
Line 2,951:
=={{header|Maxima}}==
<
[n: length(a), b: [ ], x: a[1], m: 1],
for i from 2 thru n do
Line 2,970:
"1113213211"
"31131211131221"
"13211311123113112211" */</
=={{header|MAXScript}}==
<
(
local result = ""
Line 3,002:
print num
num = lookAndSay num
)</
=={{header|Metafont}}==
<
string r; r := "";
if string s:
Line 3,027:
endfor
end</
=={{header|MiniScript}}==
<
repeats = function(digit, string)
count = 0
Line 3,052:
print number
numbers = number
end for</
{{out}}
<pre>
Line 3,069:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Assign, Length;
Line 3,109:
Assign(buf2, buf1);
END;
END LookAndSay.</
{{out}}
<pre>1
Line 3,127:
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; Compute the following number in the sequence
(define (next-number s)
Line 3,149:
;
(go 10)
</syntaxhighlight>
{{out}}
<pre>
Line 3,166:
=={{header|Nim}}==
<
var current = "1"
yield current
Line 3,184:
for s in lookAndSay(12):
echo s</
{{out}}
Line 3,202:
=={{header|Objective-C}}==
<
-(NSString*)lookAndSay:(NSString *)word{
Line 3,237:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
=== Functional ===
This function computes a see-and-say sequence from the previous one:
<
| [], nys -> List.rev nys
| x::xs, [] -> seeAndSay(xs, [x; 1])
| x::xs, y::n::nys when x=y -> seeAndSay(xs, y::1+n::nys)
| x::xs, nys -> seeAndSay(xs, x::1::nys)</
It can be used like this:
<
let xs = Array.create n [1] in
for i=1 to n-1 do
Line 3,261:
[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];
[1; 3; 2; 1; 1; 3; 1; 1; 1; 2; 3; 1; 1; 3; 1; 1; 2; 2; 1; 1]|]</
=== With regular expressions in the Str library ===
<
let lookandsay =
Line 3,277:
num := lookandsay !num;
print_endline !num;
done</
=== With regular expressions in the Pcre library ===
<
let lookandsay str =
Line 3,296:
num := lookandsay !num;
print_endline !num;
done</
run this example with 'ocaml -I +pcre pcre.cma script.ml'
=== Imperative ===
<
let look_and_say s =
Line 3,342:
*)
(* see http://oeis.org/A005341 *)</
=={{header|Oforth}}==
<
: lookAndSay ( n -- )
[ 1 ] #[ dup .cr group map( [#size, #first] ) expand ] times( n ) ;</
{{out}} for n = 10 :
Line 3,366:
=={{header|Oz}}==
<
%% e.g. "21" -> "1211"
fun {LookAndSayString S}
Line 3,395:
end
in
{ForAll {List.take {LookAndSay 1} 10} Show}</
=={{header|PARI/GP}}==
<
my(v=eval(Vec(Str(n))),cur=v[1],ct=1,out="");
v=concat(v,99);
Line 3,412:
eval(out)
};
n=1;for(i=1,20,print(n);n=step(n))</
=={{header|Pascal}}==
Line 3,418:
{{works with|Delphi}}
{{libheader|SysUtils}}
<
{$IFDEF FPC}
Line 3,460:
number := LookAndSay(number);
end;
end.</
{{out}}
<pre>% ./LookAndSay
Line 3,487:
{{works with|Free_Pascal}}
{{libheader|SysUtils}}
<
program LookAndSayDemo(input, output);
{$IFDEF FPC}
Line 3,565:
writeln(i:4,length(number):16,l2/l1:10:6);
end;
end.</
{{out}}
<pre>1
Line 3,603:
=={{header|Perl}}==
<
my $str = shift;
$str =~ s/((.)\2*)/length($1) . $2/ge;
Line 3,613:
print "$num\n";
$num = lookandsay($num);
}</
Using string as a cyclic buffer:
<
print $1;
$_ .= ($1 ne "\n" and length($1)).$2
}</
=={{header|Phix}}==
<!--<
<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>
Line 3,645:
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,662:
=={{header|PHP}}==
<
function lookAndSay($str) {
Line 3,680:
}
?></
=={{header|Picat}}==
<
S1 = "1",
foreach(_ in 1..11)
Line 3,705:
end
end,
V = S ++ C.to_string() ++ [Last].</
{{out}}
Line 3,722:
=={{header|PicoLisp}}==
<
(make
(while Lst
Line 3,728:
(while (= (setq C (pop 'Lst)) (car Lst))
(inc 'N) )
(link N C) ) ) ) )</
Usage:
<
-> (1 1)
: (las @)
Line 3,745:
-> (1 1 1 3 2 1 3 2 1 1)
: (las @)
-> (3 1 1 3 1 2 1 1 1 3 1 2 2 1)</
=={{header|PL/M}}==
<
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 3,800:
END;
CALL EXIT;
EOF</
{{out}}
<pre>1
Line 3,820:
=={{header|PowerBASIC}}==
This uses the <code>RLEncode</code> function from the [[Run-length encoding#PowerBASIC|PowerBASIC Run-length encoding entry]].
<
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM Loop0 AS LONG, count AS LONG
Line 3,864:
v = VAL(INPUTBOX$("Enter a number."))
MSGBOX lookAndSay(v)
END FUNCTION</
=={{header|PowerShell}}==
<
$re = [regex] '(.)\1*'
$ret = ""
Line 3,887:
}
}
}</
{{out}}
<pre>PS> Get-MultipleLookAndSay 8
Line 3,902:
Works with SWI-Prolog.
<
maplist(write, L), nl,
encode(L, L1),
Line 3,946:
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
</syntaxhighlight>
{{out}}
Line 3,964:
=={{header|Pure}}==
<
// Remove the trailing "L" from the string representation of bigints.
Line 3,977:
// This prints the entire sequence, press Ctrl-C to abort.
do (puts.str) (iterate say 1);</
=={{header|PureBasic}}==
<
Define i, j, cnt, txt$, curr$, result$
Print("Enter start sequence: "): txt$=Input()
Line 4,005:
PrintN(#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf</
{{out}}
Line 4,024:
=={{header|Python}}==
{{trans|C sharp|C#}}
<
result = ""
Line 4,045:
for i in range(10):
print num
num = lookandsay(num)</
Functional
{{works with|Python|2.4+}}
<
>>> def lookandsay(number):
return ''.join( str(len(list(g))) + k
Line 4,057:
>>> for i in range(10):
print numberstring
numberstring = lookandsay(numberstring)</
{{out}}
Line 4,072:
'''As a generator'''<br>
<
>>>
>>> def lookandsay(number='1'):
Line 4,091:
1113213211
31131211131221
13211311123113112211</
'''Using regular expressions'''<br>
{{trans|Perl}}
<
def lookandsay(str):
Line 4,103:
for i in range(10):
print num
num = lookandsay(num)</
=={{header|Q}}==
<
las 8</
{{Out}}
<pre>
Line 4,123:
=={{header|Quackery}}==
<
[ 1 instances put
Line 4,143:
[ dup echo$ cr
lookandsay ]
echo$ cr</
{{out}}
Line 4,168:
Returning the value as an integer limits how long the sequence can get,
so the option for integer or character return values are provided.
<
{
#convert number to character vector
Line 4,182:
#convert to number, if desired
if(return.an.int) as.integer(newstr) else newstr
}</
Example usage:
<
for(i in 1:10)
{
x <- look.and.say(x)
print(x)
}</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 4,203:
(for-each displayln (look-and-say-sequence 10))
</syntaxhighlight>
{{out}}
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.
<syntaxhighlight lang="raku"
{{out}}
Line 4,251:
===simple version===
<
parse arg N ! . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 4,272:
$= $ || _ || y /*build the "look and say" sequence. */
k= k + _ /*now, point to the next character. */
end /*k*/</
{{out|output|text= when using the default input values of: <tt> 20 1 </tt>}}
<pre>
Line 4,386:
<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.
<
parse arg N ! . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 4,413:
chSize= chSize + 100 /*bump the chunkSize (length) counter.*/
end /*k*/
return ! || $ /*return the ! string plus the $ string*/</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version (the simple version).}}<br><br>
=={{header|Ring}}==
<
number = "1"
for nr = 1 to 10
Line 4,437:
end
return o
</syntaxhighlight>
=={{header|Ruby}}==
The simplest one:
<
class String
def look_and_say
Line 4,450:
ss = '1'
12.times {puts ss; ss = ss.look_and_say}
</syntaxhighlight>
{{out}}
<pre>
Line 4,468:
{{trans|Perl}}
<
str.gsub(/(.)\1*/) {$&.length.to_s + $1}
end
Line 4,476:
puts num
num = lookandsay(num)
end</
{{out}}
<pre>
Line 4,492:
Using Enumerable#chunk
<
str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join
end
Line 4,499:
9.times do
puts num = lookandsay(num)
end</
The '''output''' is the same above.
Without regular expression:
<
module Enumerable
# clumps adjacent elements together
Line 4,520:
cluster
end
end</
Using Array#cluster defined above:
<
return unless seq > 0
puts input_sequence.join
Line 4,533:
end
print_sequence([1])</
The '''output''' is the same above.
=={{header|Rust}}==
<
assert!(!in_seq.is_empty());
Line 4,566:
seq = next_sequence(&seq);
}
}</
{{out}}
<pre>Sequence 0: [1]
Line 4,580:
=={{header|Sather}}==
<
look_and_say!: STR is
current ::= "1";
Line 4,606:
end;
end;
end;</
{{out}}
<pre>1
Line 4,624:
===Recursive===
<
object LookAndSay extends App {
Line 4,650:
}
}</
{{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===
{{libheader|Scala}}<
val s = seed.toString
( 1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
Line 4,663:
}
def lookAndSayIterator(seed: BigInt) = Iterator.iterate(seed)(lookAndSay)</
===using Stream===
<
def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = {
Line 4,682:
(lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString("")))
}</
=={{header|Seed7}}==
<
const func string: lookAndSay (in integer: level, in string: stri) is func
Line 4,712:
writeln(lookAndSay(level, "1"));
end for;
end func;</
{{out}}
Line 4,734:
=={{header|Sidef}}==
{{trans|Perl}}
<
str.gsub(/((.)\2*)/, {|a,b| a.len.to_s + b });
}
Line 4,742:
say num;
num = lookandsay(num);
} * 10;</
{{out}}
Line 4,758:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
lookAndSay [ |anElement nextElement counter coll newColl|
coll := (self asOrderedCollection).
Line 4,787:
r displayNl.
r := r lookAndSay.
]</
{{works with|Pharo}}
<
'lookAndSay |anElement nextElement counter coll newColl|
coll := (self asOrderedCollection).
Line 4,820:
]).
result.
</syntaxhighlight>
Output:
Line 4,833:
This is by far the easiest solution.
<
define('rle(str)c,n') :(rle_end)
rle str len(1) . c :f(return)
Line 4,848:
* Test and display
looksay(1,10)
end</
{{out}}
Line 4,863:
=={{header|SQL}}==
<
CREATE VIEW delta AS
SELECT sequence1.v AS x,
Line 4,909:
DELETE FROM sequence;
INSERT INTO sequence VALUES(-1,0);
INSERT INTO sequence SELECT * FROM rle;</
Usage:
Line 4,952:
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<
SET SERVEROUTPUT ON @
Line 4,993:
END WHILE;
END @
</syntaxhighlight>
Output:
<pre>
Line 5,015:
=={{header|Swift}}==
{{trans|Rust}}
<
var result = [Int]()
var cur = seq[0]
Line 5,042:
print("Seq \(i): \(seq)")
seq = lookAndSay(seq)
}</
{{out}}
Line 5,058:
=={{header|Tcl}}==
<
set new ""
while {[string length $n] > 0} {
Line 5,075:
puts [next_lookandsay] ;# ==> 1211
puts [next_lookandsay] ;# ==> 111221
puts [next_lookandsay] ;# ==> 312211</
Alternatively, with coroutines:
{{works with|Tcl|8.6}}
<
coroutine $coroName apply {n {
for {} {[yield $n] ne "stop"} {set n $new} {
Line 5,099:
puts [next_lookandsay]
puts [next_lookandsay]
puts [next_lookandsay]</
{{out}}
Line 5,116:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT,{}
num=1,say=""
Line 5,129:
IF (look==14) EXIT
ENDLOOP
</syntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 5,150:
=={{header|UNIX Shell}}==
{{works with|bash}}
<
local num=$1 char seq i
for ((i=0; i<=${#num}; i++)); do
Line 5,166:
echo $num
num=$( lookandsay $num )
done</
{{out}}
Line 5,183:
The look_and_say function returns the first n results
by iterating the function that maps a given sequence to its successor.
<
#import nat
Line 5,190:
#show+
main = look_and_say 10</
{{out}}
<pre>1
Line 5,204:
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Public Sub LookAndSay(Optional Niter As Integer = 10)
'generate "Niter" members of the look-and-say sequence
Line 5,254:
End If
End Sub
</syntaxhighlight>
{{out}}
Line 5,272:
=={{header|VBScript}}==
=====Implementation=====
<
dim i
dim accum
Line 5,291:
loop
looksay = res
end function</
=====Invocation=====
<
m = 1
for i = 0 to 13
m = looksay(m)
wscript.echo m
next</
{{out}}
Line 5,325:
10 sequences are created in this example.
<
BOL
Reg_Empty(20)
Line 5,334:
}
Ins_Newline Reg_Ins(20)
}</
{{out}}
Line 5,351:
=={{header|Vlang}}==
{{trans|Go}}
<
mut r := ''
mut c := s[0..1]
Line 5,375:
println(s)
}
}</
{{out}}
Line 5,392:
=={{header|Wren}}==
{{trans|Kotlin}}
<
var res = ""
var digit = s[0]
Line 5,412:
System.print(las)
las = lookAndSay.call(las)
}</
{{out}}
Line 5,434:
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
dim X$(2)
i = 0 // índice de cadena de entrada
Line 5,459:
next n
print
</syntaxhighlight>
{{out}}La salida es similar a la de [[#FreeBASIC|FreeBASIC]], mostrada arriba.
=={{header|Yorick}}==
<
// Special case: one digit
if(strlen(input) == 1)
Line 5,493:
write, val;
val = looksay(val);
} while(strlen(val) < 80);</
{{out}}
Line 5,515:
Treating the task as a string manipulation problem.
{{trans|Scala}}
<
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]) }
Line 5,522:
sb.write(len); sb.write(c);
sb.close();
}</
{{out}}
|