Twelve statements: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 39:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">[([Int] -> Bool)] predicates
predicates [+]= st -> st.len == 12
predicates [+]= st -> sum(st[(len)-6 ..]) == 3
Line 85:
I Int(predicate(bools)) != bools[i]
print(f:‘ (Fails at statement {i + 1:2}) {to_str(bools)}’)
L.break</langsyntaxhighlight>
 
{{out}}
Line 118:
are very handy for this task.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Logic;
 
procedure Twelve_Statements is
Line 196:
Ada.Text_IO.Put_Line("Near Misses:");
Try(T => (1..12 => False), Fail => 1);
end Twelve_Statements;</langsyntaxhighlight>
 
{{out}}
Line 223:
Here is the definition the package Logic:
 
<langsyntaxhighlight Adalang="ada">generic
Number_Of_Statements: Positive;
package Logic is
Line 238:
function Half(T: Table; Which: Even_Odd) return Table;
end Logic;</langsyntaxhighlight>
 
And here is the implementation of the "convenience functions" in Logic:
 
<langsyntaxhighlight Adalang="ada">package body Logic is
function Sum(T: Table) return Natural is
Line 268:
end Half;
 
end Logic;</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% we have 12 statements to determine the truth/falsehood of (see task) %
 
Line 366:
printSolutions( 1, "Near solutions (incorrect values marked ""*"")" );
 
end.</langsyntaxhighlight>
{{out}}
<pre>Solutions
Line 399:
The code shows all cases where we have at least S-1 matches (where S = 12 statements).
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Note: the original puzzle provides 12 statements and starts with
; "Given the following twelve statements...", so the first statement
; should ignore the F1 flag and always be true (see "( N == 1 )").
Line 474:
Return ( C == 4 )
}
}</langsyntaxhighlight>
{{out}}
<pre>11 -> 1 0 0 1 0 0 0 1 0 0 0 0
Line 498:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> nStatements% = 12
DIM Pass%(nStatements%), T%(nStatements%)
Line 540:
NEXT try%
END</langsyntaxhighlight>
{{out}}
<pre>
Line 563:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(
( number
= n done ntest oldFT
Line 827:
)
)
);</langsyntaxhighlight>
{{out}}
<pre> Solution:
Line 846:
=={{header|C sharp}}==
{{works with|C sharp|6}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 908:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>
Line 933:
=={{header|C++}}==
{{works with|gcc 5.1.0 c++11}}
<langsyntaxhighlight lang="c++">#include <iostream>
#include <vector>
#include <string>
Line 1,049:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,089:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use '[clojure.math.combinatorics]
 
(defn xor? [& args]
Line 1,108:
:when (if (= 1 (count (filter true? [g h i]))) (true? k) (false? k))
:when (if (= 4 (count (filter true? [a b c d e f g h i j k]))) (true? l) (false? l))]
[a b c d e f g h i j k l]))</langsyntaxhighlight>
 
{{out}}
Line 1,117:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defparameter *state* (make-list 12))
 
Line 1,161:
 
(defun result (?)
(format t "~:[Missed by one~;Solution:~] ~%~{~:[F~;T~] ~}~%" ? *state*))</langsyntaxhighlight>
<pre>
Missed by one
Line 1,200:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional;
 
immutable texts = [
Line 1,247:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Missed by statement: 8
Line 1,285:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,465:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,474:
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'text;
Line 1,535:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,560:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM TWELVE_STMS
 
Line 1,619:
 
END FOR ! TRY%
END PROGRAM</langsyntaxhighlight>
{{out}}<pre>
Near miss with statements 1 4 true (failed 8 ).
Line 1,642:
=={{header|Forth}}==
Forth is excellently suited to solve this, because it has excellent support for manipulating bitpatterns.
<langsyntaxhighlight lang="forth">: lastbit ( n1 -- n2)
dup if 1 swap begin dup 1 <> while swap 1+ swap 1 rshift repeat drop then
;
Line 1,684:
;
 
12statements</langsyntaxhighlight>
{{out}}
<pre>
Line 1,710:
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="freebasic">Dim As Integer nEnunciados = 12, intento, enun, errado
Dim As Integer Afirm(nEnunciados), T(nEnunciados)
 
Line 1,754:
End Select
Next intento
Sleep</langsyntaxhighlight>
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,884:
solution <- tz
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,908:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">enum Rule {
r01( 1, { r()*.num == (1..12) }),
r02( 2, { r(7..12).count { it.truth } == 3 }),
Line 1,962:
}
 
Rule.evaluate()</langsyntaxhighlight>
 
{{out}}
Line 1,986:
Shows answers with 1 for true, followed by list of indices of contradicting elements in each set of 1/0s (index is 0-based).
 
<langsyntaxhighlight lang="haskell">import Data.List (findIndices)
 
tf :: [[Int] -> Bool] -> [[Int]]
Line 2,027:
mapM_ print $ t 0
putStrLn "Near misses"
mapM_ print $ t 1</langsyntaxhighlight>
{{out}}
<pre>
Line 2,053:
=={{header|J}}==
In the following 'apply' is the foreign conjunction:
<langsyntaxhighlight lang="j"> apply
128!:2
 
NB. example
'*:' apply 1 2 3
1 4 9</langsyntaxhighlight>
This enables us to apply strings (left argument) being verbs to the right argument, mostly a noun.
<langsyntaxhighlight lang="j">S=: <;._2 (0 :0)
12&=@# NB. 1. This is a numbered list of twelve statements.
3=+/@:{.~&_6 NB. 2. Exactly 3 of the last 6 statements are true.
Line 2,075:
)
 
testall=: (];"1 0<@I.@:(]~:(apply&><))"1) #:@i.@(2&^)@#</langsyntaxhighlight>
 
The output follows the Haskell convention: true/false bitstring followed by the index of a contradiction
 
'''All true'''
<langsyntaxhighlight lang="j"> (#~0=#@{::~&_1"1) testall S
┌───────────────────────┬┐
│1 0 1 1 0 1 1 0 0 0 1 0││
└───────────────────────┴┘</langsyntaxhighlight>
Or, numerically:
<langsyntaxhighlight lang="j"> 1+I.;(#~0=#@{::~&_1"1) testall S
1 3 4 6 7 11</langsyntaxhighlight>
 
'''Near misses'''
<langsyntaxhighlight lang="j"> (#~1=#@{::~&_1"1) testall S
┌───────────────────────┬──┐
│0 0 0 0 1 0 0 1 0 0 1 0│0 │
Line 2,122:
├───────────────────────┼──┤
│1 1 0 1 0 0 1 1 1 0 0 0│7 │
└───────────────────────┴──┘</langsyntaxhighlight>
 
'''Iterative for all true'''
<br>A repeat while true approach: x f^:(p)^:_ y
<langsyntaxhighlight lang="j"> (-N)&{. #: S <:@]^:((]-.@-:(apply&><)"1) (-N)&{.@#:@])^:(_) 2^N=.#S
1 0 1 1 0 1 1 0 0 0 1 0</langsyntaxhighlight>
 
Here is an alternative representation of the statements which might be slightly easier to read. (The behavior is identical):
 
<langsyntaxhighlight lang="j">true=:1 :'(m-1)&{'
 
S=: <;._2 (0 :0)
Line 2,146:
1 (= +/) 7 8 9 true NB. 11. Exactly 1 of statements 7, 8 and 9 are true.
4 (= +/) }: NB. 12. Exactly 4 of the preceding statements are true.
)</langsyntaxhighlight>
 
And here is an approach which does not use the verb apply, but instead mostly relies on simple arithmetic.
 
<langsyntaxhighlight lang="j">'sum not mask'=: |:".;._2(0 :0)
0; 0; 0 0 0 0 0 0 0 0 0 0 0 0 NB. 1. This is a numbered list of twelve statements.
3; 0; 0 0 0 0 0 0 1 1 1 1 1 1 NB. 2. Exactly 3 of the last 6 statements are true.
Line 2,166:
propositions=: |:#:i.2^#sum
 
errors=: propositions~:(1 - not { 1,propositions) >. sum = mask +/ .*propositions</langsyntaxhighlight>
 
Now, as before, we can find the consistent set of true and false values:
 
<langsyntaxhighlight Jlang="j"> #:I.0=+/errors
1 0 1 1 0 1 1 0 0 0 1 0
1+I.#:I.0=+/errors NB. true propositions for the consistent case
1 3 4 6 7 11</langsyntaxhighlight>
 
And, we can find the set which is inconsistent for only one proposition:
 
<langsyntaxhighlight Jlang="j"> offby1=: 1=+/errors
'Statement ',"1 (":1+I.|: offby1 #"1 errors),"1 ' is inconsistent with exactly ',"1 ((1":@:+I.)"1 #:I.offby1),"1 ' being true'
Statement 1 is inconsistent with exactly 5 8 11 being true
Line 2,194:
Statement 12 is inconsistent with exactly 1 2 4 7 9 12 being true
Statement 10 is inconsistent with exactly 1 2 4 7 9 10 being true
Statement 8 is inconsistent with exactly 1 2 4 7 8 9 being true</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,200:
The following Java code uses brute force. It tries to translate the logical statements as naturally as possible. The run time is almost zero.
 
<syntaxhighlight lang="java">
<lang Java>
public class LogicPuzzle
{
Line 2,314:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,338:
for a specific "select every nth item" filter, but also for a
generic "with_index" annotator.
<langsyntaxhighlight lang="jq">def indexed(filter):
. as $in
| reduce range(0;length) as $i ([]; if ($i | filter) then . + [$in[$i]] else . end);
Line 2,388:
# number of exact and off-by-one solutions:
 
task | length</langsyntaxhighlight>
{{out}}
$ jq -M -n -f Twelve_statements.jq
Line 2,395:
=={{header|Julia}}==
This task involves only 12 statements, so an exhaustive search of the 2^12 possible statement value combinations is quite feasible. The program shows "total misses" and the distribution of numbers of hits in addition to solutions and near misses.
<langsyntaxhighlight Julialang="julia">using Printf
 
function showflaggedbits{T<:BitArray{1}}(a::T, f::T)
Line 2,451:
println(@sprintf " %2d => %4d" i-1 mhist[i])
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,496:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Predicate = (String) -> Boolean
Line 2,540:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,567:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Print["Answer:\n", Column@Cases[#, {s_, 0} :> s], "\nNear misses:\n",
Column@Cases[#, {s_, 1} :> s]] &[{#,
Count[Boole /@ {Length@# == 12, Total@#[[7 ;;]] == 3,
Line 2,576:
Total@#[[;; 6]] == 3, #[[11]] + #[[12]] == 2,
Total@#[[7 ;; 9]] == 1, Total@#[[;; 11]] == 4} - #,
Except[0]]} & /@ Tuples[{1, 0}, 12]]</langsyntaxhighlight>
{{Out}}
<pre>Answer:
Line 2,603:
Not quite a translation as we use an array of booleans instead of a string. There are also other differences but the final result is the same.
 
<langsyntaxhighlight Nimlang="nim">import bitops, sequtils, strformat, strutils, sugar
 
type Bools = array[1..12, bool]
Line 2,645:
if predicate(bools) != bools[i]:
echo &" (Fails at statement {i:2}) {bools}"
break</langsyntaxhighlight>
 
{{out}}
Line 2,674:
Inspired by the C++ implementation, this version makes extensive use of Pascal's built-in set handling capabilities.
 
<langsyntaxhighlight lang="pascal">PROGRAM TwelveStatements;
 
{
Line 2,805:
writeln('Done. Press ENTER.');
readln
END.</langsyntaxhighlight>
 
{{Out}}
Line 2,812:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util 'sum';
 
my @condition = (
Line 2,840:
print "1 miss (",$no[0],"): true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 1 == @no;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1 miss (1): true statements are 5 8 11
Line 2,862:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">s1</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;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">12</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">s2</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;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">7</span><span style="color: #0000FF;">..</span><span style="color: #000000;">12</span><span style="color: #0000FF;">],</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">3</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Line 2,893:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">misses</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,919:
{{trans|Prolog}}
 
<langsyntaxhighlight Picatlang="picat">% {{trans|Prolog}}
go ?=>
puzzle,
Line 2,969:
println('L'=L),
printf("Statements %w are true.\n", [I.to_string : I in 1..12, L[I] == 1].join(" ")),
nl.</langsyntaxhighlight>
 
{{out}}
Line 2,978:
=={{header|Prolog}}==
Works with '''SWI-Prolog''' and '''library(clpfd)'''.
<langsyntaxhighlight Prologlang="prolog">puzzle :-
% 1. This is a numbered list of twelve statements.
L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12],
Line 3,029:
 
my_write(_N, 0).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- puzzle.
Line 3,042:
Python's boolean type <tt>bool</tt>is a subclass of <tt>int</tt>, so boolean values True, False can be used as integers (1, 0, respectively) in numerical contexts.
This fact is used in the lambda expressions that use function sum.
<langsyntaxhighlight lang="python">
from itertools import product
#from pprint import pprint as pp
Line 3,082:
 
for stm in full + partial:
printer(*stm)</langsyntaxhighlight>
 
{{out}}
Line 3,124:
This question really begs to be done with <tt>amb</tt>
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,192:
;; -> '(1 3 4 6 7 11)
 
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>sub infix:<→> ($protasis, $apodosis) { !$protasis or $apodosis }
my @tests =
Line 3,231:
say "";
say "Near misses:";
.say for @misses;</langsyntaxhighlight>
 
{{out}}
Line 3,256:
=={{header|REXX}}==
===generalized logic===
<langsyntaxhighlight lang="rexx">/*REXX program solves the "Twelve Statement Puzzle". */
q=12; @stmt=right('statement',20) /*number of statements in the puzzle. */
m=0 /*[↓] statement one is TRUE by fiat.*/
Line 3,286:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
yeses: parse arg L,H,B; #=0; do i=L to H by word(B 1, 1); #=#+@.i; end; return #</langsyntaxhighlight>
'''output'''
<pre>
Line 3,298:
 
===discrete logic===
<langsyntaxhighlight lang="rexx">/*REXX program solves the "Twelve Statement Puzzle". */
q=12; @stmt=right('statement',20) /*number of statements in the puzzle. */
m=0 /*[↓] statement one is TRUE by fiat.*/
Line 3,326:
end /*tell*/
end /*e*/
end /*pass*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> version.
<br><br>
 
===optimized===
<langsyntaxhighlight lang="rexx">/*REXX program solves the "Twelve Statement Puzzle". */
q=12; @stmt=right('statement',20) /*number of statements in the puzzle. */
m=0 /*[↓] statement one is TRUE by fiat.*/
Line 3,357:
end /*j*/
end /*e*/
end /*pass*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> version.
<br><br>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">constraints = [
->(st) { st.size == 12 },
->(st) { st.last(6).count(true) == 3 },
Line 3,390:
near_misses.each do |r|
puts "missed by statement #{r.consistency.index(false) + 1}", r.truths.to_s
end</langsyntaxhighlight>
 
{{out}}
Line 3,435:
===Imperative Programming (Ugly)===
{{trans|Java}}
<langsyntaxhighlight Scalalang="scala">class LogicPuzzle {
val s = new Array[Boolean](13)
var count = 0
Line 3,515:
println(s"${p.count} Solutions found.")
 
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scastie.scala-lang.org/XaRsz8gOQxavQ5rwMxi9ZA Scastie (JVM)] or
by [https://scalafiddle.io/sf/x73tnT6/1 ScalaFiddle (JavaScript)].
Line 3,521:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var conditions = [
{ false },
{|a| a.len == 13 },
Line 3,546:
no.len == 0 && say "Solution: true statements are #{1..12->grep{t[_]}.join(' ')}"
no.len == 1 && say "1 miss (#{no[0]}): true statements are #{1..12->grep{t[_]}.join(' ')}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,681:
=={{header|Tcl}}==
{{works with|Tcl|8.6}} <!-- but not 8.6b3; the lmap command post-dates that release -->
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# Function to evaluate the truth of a statement
Line 3,753:
foreach {state j} $differ {
puts "almost found\t[renderstate $state] \u21d2 [expr {[lindex $state $j-1]?"\u00ac":{}}]S($j)"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,777:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txrlisp">(defmacro defconstraints (name size-name (var) . forms)
^(progn (defvar ,size-name ,(length forms))
(defun ,name (,var)
Line 3,812:
 
(each ((r results))
(put-line `@r`))</langsyntaxhighlight>
 
{{out}}
Line 3,830:
=={{header|uBasic/4tH}}==
{{trans|BBC Basic}}
<syntaxhighlight lang="text">S = 12
For T = 0 To (2^S)-1
 
Line 3,893:
Loop
 
Return</langsyntaxhighlight>
Output:
<pre>Near miss with statements 1 4 true (failed 8).
Line 3,914:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Public s As String '-- (eg "101101100010")
Public t As Integer '-- scratch
Line 4,000:
Next
Next
End Sub</langsyntaxhighlight>{{out}}
<pre>Found solution:101101100010</pre>
 
Line 4,006:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Conv, Fmt
 
var predicates = [
Line 4,058:
show.call(s, false)
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,086:
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight Yabasiclang="yabasic">sub s1() return len(s$)=12 end sub
sub s2() local t, i : t=0 : for i=7 to 12 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=3 end sub
sub s3() local t, i : t=0 : for i=2 to 12 step 2 : t = t + (mid$(s$, i, 1) <> "0") : next : return t=2 end sub
Line 4,110:
if b=12 print s$
next
next</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var statements; // list of 13 Bools, statements[0] is garbage to make 1 based
fcn s0 { False } // dummy for padding
fcn s1 { True }
Line 4,142:
(12).pump(List,'wrap(n){ statements[n] and n or Void.Skip })
.concat(",").println(" : ",vm.pasteArgs());
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits