Set puzzle: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Picat}}: Added subsection)
m (syntax highlighting fixup automation)
Line 80:
We start with the specification of a package "Set_Puzzle.
 
<langsyntaxhighlight Adalang="ada">package Set_Puzzle is
type Three is range 1..3;
Line 97:
-- calls Do_Something once for each set it finds.
end Set_Puzzle;</langsyntaxhighlight>
 
Now we implement the package "Set_Puzzle".
 
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
package body Set_Puzzle is
Line 178:
begin
Rand.Reset(R);
end Set_Puzzle;</langsyntaxhighlight>
 
Finally, we write the main program, using the above package. It reads two parameters from the command line. The first parameter describes the number of cards, the second one the number of sets. Thus, for the basic mode one has to call "puzzle 9 4", for the advanced mode "puzzle 12 6", but the program would support any other combination of parameters just as well.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Set_Puzzle, Ada.Command_Line;
 
procedure Puzzle is
Line 231:
Print_Sets(Cards); -- print the sets
end Puzzle;</langsyntaxhighlight>
 
{{out}}
Line 263:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">; Generate deck; card encoding from Raku
Loop, 81
deck .= ToBase(A_Index-1, 3)+1111 ","
Line 366:
c%j% += 1
}
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>Dealt 9 cards:
Line 446:
=={{header|C}}==
Brute force. Each card is a unique number in the range of [0,81]. Randomly deal a hand of cards until exactly the required number of sets are found.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 540:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
{{works with|C sharp|8}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 628:
static bool AreSameOrDifferent(int a, int b, int c) => (a + b + c) % 3 == 0;
static IEnumerable<int> To(this int start, int end) => Range(start, end - start - 1);
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 673:
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">
#include <time.h>
#include <algorithm>
Line 805:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 880:
=={{header|Ceylon}}==
Add import ceylon.random "1.3.3" to your module.ceylon file
<langsyntaxhighlight lang="ceylon">import ceylon.random {
Random,
DefaultRandom
Line 1,019:
}
 
}</langsyntaxhighlight>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.array, std.conv, std.traits,
std.exception, std.range, std.algorithm;
 
Line 1,118:
writefln("\nFOUND %d SET%s:", len, len == 1 ? "" : "S");
writefln("%(%(%s\n%)\n\n%)", sets);
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>DEALT 9 CARDS:
Line 1,150:
===Short Version===
This requires the third solution module of the Combinations Task.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.random, combinations3;
 
Line 1,168:
writefln("Dealt %d cards:\n%(%-(%8s %)\n%)\n", draw.length, draw);
writefln("Containing:\n%(%(%-(%8s %)\n%)\n\n%)", sets);
}</langsyntaxhighlight>
{{out}}
<pre>Dealt 9 cards:
Line 1,199:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(require 'list)
 
Line 1,250:
))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,311:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def set_puzzle(deal, goal) do
{puzzle, sets} = get_puzzle_and_answer(deal, goal, produce_deck)
Line 1,364:
 
RC.set_puzzle(9, 4)
RC.set_puzzle(12, 6)</langsyntaxhighlight>
 
{{out}}
Line 1,438:
=={{header|Erlang}}==
Until a better solution is found this is one.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( set ).
 
Line 1,522:
make_sets_acc( true, Set, Sets ) -> [Set | Sets];
make_sets_acc( false, _Set, Sets ) -> Sets.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,582:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
type Number = One | Two | Three
Line 1,663:
solve 12 6
 
playGame()</langsyntaxhighlight>
Output:
<pre>
Line 1,734:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays backtrack combinators.short-circuit formatting
fry grouping io kernel literals math.combinatorics math.matrices
prettyprint qw random sequences sets ;
Line 1,775:
12 6 set-puzzle ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre style="height:65ex">
Line 1,847:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,920:
fmt.Printf(" %s\n %s\n %s\n",s[0],s[1],s[2])
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,992:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad.State
(State, evalState, replicateM, runState, state)
import System.Random (StdGen, newStdGen, randomR)
Line 2,094:
main = do
showSolutions 9 4
showSolutions 12 6</langsyntaxhighlight>
{{out}}
<pre style="font-size:80%">Showing hand of 9 cards with 4 solutions.
Line 2,167:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'stats/base'
 
Number=: ;:'one two three'
Line 2,190:
echo LF,'Found ',(":target),' Sets:'
echo sayCards sort"2 getSets Hand
)</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="j"> set_puzzle 9
Dealt 9 Cards:
one, red, solid, oval
Line 2,220:
three, red, open, oval
three, green, solid, oval
three, purple, striped, oval </langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.*;
 
public class SetPuzzle {
Line 2,353:
return tot == 0;
}
}</langsyntaxhighlight>
<pre>GIVEN 12 CARDS:
 
Line 2,397:
=={{header|Julia}}==
Plays one basic game and one advanced game.
<langsyntaxhighlight lang="julia">using Random, IterTools, Combinatorics
 
function SetGameTM(basic = true)
Line 2,440:
SetGameTM()
SetGameTM(false)
</langsyntaxhighlight> {{output}} <pre>
Dealt 9 cards:
("green", "one", "oval", "open")
Line 2,510:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
import java.util.Collections.shuffle
Line 2,598:
println()
playGame(Degree.ADVANCED)
}</langsyntaxhighlight>
 
Sample output:
Line 2,678:
A simple brute force approach. This code highlights two things: 1) a few of Mathematica's "higher-level" functions such as Tuples and Subsets and 2) the straightforwardness enabled by the language's "dynamic typing" (more precisely, its symbolic semantics) and its usage of lists for everything (in this particular example, the fact that functions such as Tuples and Entropy can be used on lists with arbitrary content).
 
<langsyntaxhighlight Mathematicalang="mathematica">colors = {Red, Green, Purple};
symbols = {"0", "\[TildeTilde]", "\[Diamond]"};
numbers = {1, 2, 3};
Line 2,693:
count = Count[Subsets[cards, {3}], _?validSetQ]];
cards];
Row[{Style[#2, #1], #3, #4}] & @@@ deal[{9, 4}]</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import algorithm, math, random, sequtils, strformat, strutils
 
type
Line 2,777:
playGame(Basic)
echo()
playGame(Advanced)</langsyntaxhighlight>
 
{{out}}
Line 2,853:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dealraw(cards)=vector(cards,i,vector(4,j,1<<random(3)));
howmany(a,b,c)=hammingweight(bitor(a,bitor(b,c)));
name(v)=Str(["red","green",0,"purple"][v[1]],", ",["oval","squiggle",0,"diamond"][v[2]],", ",["one","two",0,"three"][v[3]],", ",["solid","open",0,"striped"][v[4]]);
Line 2,880:
};
deal(9,4)
deal(12,6)</langsyntaxhighlight>
{{output}}
<pre>green, diamond, one, open
Line 2,950:
It's actually slightly simplified, since generating Enum classes
and objects would be overkill for this particular task.
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 3,029:
 
__END__
</syntaxhighlight>
</lang>
{{out}}
<pre>Drew 12 cards:
Line 3,059:
=={{header|Phix}}==
Converts cards 1..81 (that idea from C) to 1/2/4 [/7] (that idea from Perl) but inverts the validation
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">comb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">pool</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">needed</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">={},</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">done</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">chosen</span><span style="color: #0000FF;">={})</span>
Line 3,127:
<span style="color: #000080;font-style:italic;">--play(12,6)
--play(9,6)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,161:
=={{header|Picat}}==
The problem generator check that it problem has exactly one solution, so that step can take a little time (some seconds). <code>fail/0</code> is used to check for unicity of the solution.
<langsyntaxhighlight Picatlang="picat">import util.
import cp.
 
Line 3,334:
],
SetLen = 3,
Wanted = 4.</langsyntaxhighlight>
 
 
Line 3,403:
===Constraint model===
Here is the additional code for a '''constraint model'''. Note that the constraint solver only handles integers so the features must be converted to integers. To simplify, the random instance generator does not check for unicity of the problem instance, so it can have (and often have) a lot of solutions.
<langsyntaxhighlight Picatlang="picat">go4 =>
NumCards = 18,
NumWanted = 9,
Line 3,485:
%
generate_instance2(NumCards,_NumSets,_SetLen, Cards) =>
Cards = random_deal(NumCards).</langsyntaxhighlight>
 
{{out}}
Line 3,537:
=={{header|Prolog}}==
 
<langsyntaxhighlight Prologlang="prolog">do_it(N) :-
card_sets(N, Cards, Sets),
!,
Line 3,581:
match([A|T1],[B|T2],[C|T3]) :-
dif(A,B), dif(B,C), dif(A,C),
match(T1,T2,T3).</langsyntaxhighlight>
{{out}}
<pre>
Line 3,659:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/python
from itertools import product, combinations
Line 3,705:
break
printit(deal, sets)
</syntaxhighlight>
</lang>
<small>Note: You could remove the inner square brackets of the <code>'if all( [...] )'</code> part of the sets computation in the getsets function. It is a remnant of Python 2.7 debugging which gives access to the name <code>feature</code>. The code works on Python 3.X too, but not that access.</small>
 
Line 3,739:
===Short Version===
{{trans|D}}
<langsyntaxhighlight lang="python">import random, pprint
from itertools import product, combinations
 
Line 3,759:
pprint.pprint(draw)
print "\nContaining %d sets:" % len(sets)
pprint.pprint(sets)</langsyntaxhighlight>
{{out}}
<pre>Dealt 9 cards:
Line 3,787:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,824:
(deal 9 4)
(deal 12 6)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,830:
 
The trick here is to allocate three different bits for each enum, with the result that the cards of a matching set OR together to produce a 4-digit octal number that contains only the digits 1, 2, 4, or 7. This OR is done by funny looking <tt>[+|]</tt>, which is the reduction form of <tt>+|</tt>, which is the numeric bitwise OR. (Because Raku stole the bare <tt>|</tt> operator for composing junctions instead.)
<syntaxhighlight lang="raku" perl6line>enum Color (red => 0o1000, green => 0o2000, purple => 0o4000);
enum Count (one => 0o100, two => 0o200, three => 0o400);
enum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40);
Line 3,857:
show-cards @cards;
}
}</langsyntaxhighlight>
{{out}}
<pre>Drew 9 cards:
Line 3,897:
 
The particular set of cards dealt (show below) used Regina 3.9.3 under a Windows/XP environment.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays "sets" (solutions) for the SET puzzle (game). */
parse arg game seed . /*get optional # cards to deal and seed*/
if game=='' | game=="," then game= 9 /*Not specified? Then use the default.*/
Line 4,014:
/*──────────────────────────────────────────────────────────────────────────────────────*/
sey: if \tell then return /*¬ tell? Then suppress the output. */
if arg(2)==. then say; say arg(1); if arg(3)==. then say; return</langsyntaxhighlight>
'''output''' when using the default input:
<pre>
Line 4,065:
=={{header|Ruby}}==
Brute force.
<langsyntaxhighlight lang="ruby">COLORS = %i(red green purple) #use [:red, :green, :purple] in Ruby < 2.0
SYMBOLS = %i(oval squiggle diamond)
NUMBERS = %i(one two three)
Line 4,100:
 
set_puzzle(9)
set_puzzle(12)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,171:
</pre>
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use itertools::Itertools;
use rand::Rng;
Line 4,272:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,316:
=={{header|Tailspin}}==
Dealing cards at random to the size of the desired hand, then trying again if the desired set count is not achieved.
<langsyntaxhighlight lang="tailspin">
def deck: [ { by 1..3 -> (colour: $),
by 1..3 -> (symbol: $),
Line 4,373:
 
[9,4] -> setPuzzle -> formatSets -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,395:
 
Twelve cards with six sets
<langsyntaxhighlight lang="tailspin">
[12,6] -> setPuzzle -> formatSets -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,426:
The principle behind this code is that the space of possible solutions is a substantial proportion of the space of possible hands, so picking a random hand and verifying that it is a solution, repeating until that verification succeeds, is a much quicker way to find a solution than a systematic search.
It also makes the code substantially simpler.
<langsyntaxhighlight lang="tcl"># Generate random integer uniformly on range [0..$n-1]
proc random n {expr {int(rand() * $n)}}
 
Line 4,507:
}
return [list $hand $sets]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl"># Render a hand (or any list) of cards (the "."s are just placeholders).
proc PrettyHand {hand {separator \n}} {
set Co {. red green . purple}
Line 4,537:
PrettyOutput [SetPuzzle 9 4]
puts "=== ADVANCED PUZZLE ======"
PrettyOutput [SetPuzzle 12 6]</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 4,615:
{{libheader|Wren-math}}
{{libheader|Wren-sort}}
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Enum
import "/trait" for Comparable
import "/fmt" for Fmt
Line 4,725:
playGame.call(Degree.BASIC)
System.print()
playGame.call(Degree.ADVANCED)</langsyntaxhighlight>
 
{{out}}
Line 4,805:
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">const nDraw=9, nGoal=(nDraw/2); // Basic
var [const] UH=Utils.Helpers; // baked in stash of goodies
deck:=Walker.cproduct("red green purple".split(), // Cartesian product of 4 lists of lists
Line 4,826:
draw.pump(Void,fcn(card){ println(("%8s "*4).fmt(card.xplode())) });
println("\nContaining:");
sets.pump(Void,fcn(card){ println((("%8s "*4 + "\n")*3).fmt(card.xplode())) });</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits