Self-describing numbers: Difference between revisions
→{{header|Picat}}: Split into subsections.
(→{{header|Picat}}: Split into subsections.) |
|||
Line 2,108:
=={{header|Picat}}==
Here are three approaches. The latter two use a constraint modelling approach (a variant to the classic '''magic sequence''' problem, see below).▼
* self_desc_cp/2: Checks if a number is a self-describing number.▼
===Loop based approach===
▲The latter two use a constraint modelling approach (a variant to the classic '''magic sequence''' problem, see below).
<lang Picat>self_desc(Num,L) =>▼
▲self_desc(Num,L) =>
L = [ I.to_integer() : I in Num.to_string()],
Len = L.len,
Line 2,132 ⟶ 2,123:
fail
end
end.</lang>
▲% Constraint model.
<lang Picat>self_desc_cp(Num, Sequence) =>▼
▲self_desc_cp(Num, Sequence) =>
N = length(Num.to_string()),
Line 2,150 ⟶ 2,139:
scalar_product({ I : I in 0..N-1}, Sequence, N),
solve([ffd,updown], Sequence).</lang>
▲% Constraint model.
<lang Picat>self_desc_cp_len(Len, Num) =>▼
▲% Same idea as self_desc_cp/2 but a different usage: generate all solutions of a specific length Len.
▲self_desc_cp_len(Len, Num) =>
Sequence = new_list(Len),
Line 2,167 ⟶ 2,154:
solve([ffc,inout], Sequence).
%
Line 2,176 ⟶ 2,162:
Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]).</lang>
===Testing===
Testing some numbers using <code>self_desc_cp/2</code>:
<lang Picat>go =>
List = [1210, 2020, 21200, 3211000, 42101000,
Line 2,201 ⟶ 2,187:
</pre>
Using <code>self_desc_cp_len/3</code> to generates all solutions of length 1..13:
<lang Picat>go2 =>
Len :: 1..13,
Line 2,211 ⟶ 2,198:
<pre>[1210,2020,21200,3211000,42101000,521001000,6210001000,72100001000,821000001000,9210000001000]</pre>
===Magic sequence===
The two constraint modelling approaches are
''A magic sequence of length n is a sequence of integers x0 . . xn-1 between
Line 2,277 ⟶ 2,265:
...</pre>
===Algorithmic approach===
Except for the self describing number 2020, these sequences can be found by the following "algorithmic" approach:
<lang Picat>magic_sequence_alg(N, Sequence) =>
Line 2,285 ⟶ 2,273:
Sequence[3] := 1,
Sequence[N-3] := 1.</lang>
=={{header|PicoLisp}}==
|