Wordle comparison: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Wordle comparison in FreeBASIC)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(22 intermediate revisions by 13 users not shown)
Line 1:
{{Draft task}}
 
;Rationale:
Line 17:
<br><br>
 
=={{header|ALGOL 68}}==
 
Test cases copied from '''C'''.
<syntaxhighlight lang="algol68"># utility functions: #
 
PROC join = ([]STRING row, STRING joiner) STRING:
BEGIN
BOOL first := TRUE;
STRING result := "";
FOR i FROM LWB row TO UPB row DO
IF NOT first THEN result +:= joiner
ELSE first := FALSE
FI;
result +:= row[i]
OD;
result
END;
 
PROC fill = (REF []STRING row, STRING s) VOID:
BEGIN
FOR i FROM LWB row TO UPB row DO row[i] := s OD
END;
 
# actual solution: #
 
PROC wordle comparison = (STRING word, guess) []STRING:
BEGIN
STRING copy := word;
# we'll just replace matched chars with NULs in copy
to avoid further matches #
[UPB guess]STRING result;
fill(result, "");
# first the greens: #
FOR i TO UPB guess DO
IF i <= UPB copy AND copy[i] = guess[i] THEN
result[i] := "green";
copy[i] := REPR 0
FI
OD;
# then the rest: #
FOR i TO UPB guess DO
IF result[i] = "" THEN
FOR j TO UPB copy DO
IF copy[j] = guess[i] THEN
result[i] := "yellow";
copy[j] := REPR 0;
next
FI
OD;
result[i] := "grey";
next: SKIP
FI
OD;
result
END;
 
[,]STRING pairs = (("ALLOW", "LOLLY"),
("BULLY", "LOLLY"),
("ROBIN", "ALERT"),
("ROBIN", "SONIC"),
("ROBIN", "ROBIN"));
FOR i TO UPB pairs DO
print((pairs[i,1], " v ", pairs[i,2], " => ",
join(wordle comparison(pairs[i,1], pairs[i,2]), ", "),
newline))
OD</syntaxhighlight>
 
{{out}}
<pre>ALLOW v LOLLY => yellow, yellow, green, grey, grey
BULLY v LOLLY => grey, grey, green, green, green
ROBIN v ALERT => grey, grey, grey, yellow, grey
ROBIN v SONIC => grey, green, yellow, green, grey
ROBIN v ROBIN => green, green, green, green, green</pre>
 
=={{header|C}}==
{{trans|Wren}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 74 ⟶ 147:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 85 ⟶ 158:
</pre>
 
=={{header|C#}}==
{{works with|.NET 8}}
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Linq;
 
public class WordleComparison
{
public static void Main(string[] args)
{
List<TwoWords> pairs = new List<TwoWords>
{
new TwoWords("ALLOW", "LOLLY"),
new TwoWords("ROBIN", "SONIC"),
new TwoWords("CHANT", "LATTE"),
new TwoWords("We're", "She's"),
new TwoWords("NOMAD", "MAMMA")
};
 
foreach (var pair in pairs)
{
Console.WriteLine(pair.Answer + " v " + pair.Guess + " -> " + string.Join(", ", Wordle(pair.Answer, pair.Guess)));
}
}
 
private static List<Colour> Wordle(string answer, string guess)
{
if (answer.Length != guess.Length)
{
throw new ArgumentException("The two words must be of the same length.");
}
 
var result = Enumerable.Repeat(Colour.GREY, guess.Length).ToList();
var answerCopy = answer;
 
for (int i = 0; i < guess.Length; i++)
{
if (answer[i] == guess[i])
{
answerCopy = answerCopy.Remove(i, 1).Insert(i, "\0");
result[i] = Colour.GREEN;
}
}
 
for (int i = 0; i < guess.Length; i++)
{
int index = answerCopy.IndexOf(guess[i]);
if (index >= 0 && result[i] != Colour.GREEN)
{
answerCopy = answerCopy.Remove(index, 1).Insert(index, "\0");
result[i] = Colour.YELLOW;
}
}
 
return result;
}
 
private enum Colour { GREEN, GREY, YELLOW }
 
private record TwoWords(string Answer, string Guess);
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> YELLOW, YELLOW, GREEN, GREY, GREY
ROBIN v SONIC -> GREY, GREEN, YELLOW, GREEN, GREY
CHANT v LATTE -> GREY, YELLOW, YELLOW, GREY, GREY
We're v She's -> GREY, GREY, YELLOW, YELLOW, GREY
NOMAD v MAMMA -> GREY, YELLOW, GREEN, GREY, GREY
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
 
enum Colour { GREEN, GREY, YELLOW };
 
const char NIL = '\0';
 
struct Two_Words {
std::string answer;
std::string guess;
};
 
std::string to_string(const Colour& colour) {
std::string result;
switch ( colour ) {
case Colour::GREEN : result = "Green"; break;
case Colour::GREY : result = "Grey"; break;
case Colour::YELLOW : result = "Yellow"; break;
}
return result;
}
 
std::vector<Colour> wordle(const std::string& answer, const std::string& guess) {
const uint32_t guess_length = guess.length();
if ( answer.length() != guess_length ) {
throw std::invalid_argument("The two words must have the same length.");
}
 
std::string answerCopy = answer;
std::vector<Colour> result(guess_length, Colour::GREY);
for ( uint32_t i = 0; i < guess_length; ++i ) {
if ( answer[i] == guess[i] ) {
answerCopy[i] = NIL;
result[i] = Colour::GREEN;
}
}
 
for ( uint32_t i = 0; i < guess_length; ++i ) {
std::string::size_type index = answerCopy.find(guess[i]);
if ( index != std::string::npos ) {
answerCopy[index] = NIL;
result[i] = Colour::YELLOW;
}
}
return result;
}
 
int main() {
const std::vector<Two_Words> pairs = { Two_Words("ALLOW", "LOLLY"), Two_Words("ROBIN", "SONIC"),
Two_Words("CHANT", "LATTE"), Two_Words("We're", "She's"), Two_Words("NOMAD", "MAMMA") };
 
for ( const Two_Words& pair : pairs ) {
std::vector<Colour> colours = wordle(pair.answer, pair.guess);
std::cout << pair.answer << " v " << pair.guess << " -> [";
for ( uint32_t i = 0; i < pair.answer.length() - 1; ++i ) {
std::cout << to_string(colours[i]) << ", ";
}
std::cout << to_string(colours.back()) << "]" << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
ALLOW v LOLLY -> [Yellow, Yellow, Green, Grey, Grey]
ROBIN v SONIC -> [Grey, Green, Yellow, Green, Grey]
CHANT v LATTE -> [Grey, Yellow, Yellow, Grey, Grey]
We're v She's -> [Grey, Grey, Yellow, Yellow, Grey]
NOMAD v MAMMA -> [Grey, Yellow, Green, Grey, Grey]
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
{Structure to hold the secret wordle word and a test word}
 
type TStringPair = record
Secret,Test: string;
end;
 
{Array of test pairs}
 
const Pairs: array [0..4] of TStringPair = (
(Secret: 'ALLOW'; Test: 'LOLLY'),
(Secret: 'BULLY'; Test: 'LOLLY'),
(Secret: 'ROBIN'; Test: 'ALERT'),
(Secret: 'ROBIN'; Test: 'SONIC'),
(Secret: 'ROBIN'; Test: 'ROBIN'));
 
{Structures holding wordle colors}
 
type TWordleColors = (wcGreen,wcYellow,wcGrey);
type TWordleArray = array [0..4] of TWordleColors;
 
 
function TestWordle(Secret,Test: string): TWordleArray;
{Compare Test string against secret wordle word}
var I,J,Inx: integer;
var SL: TStringList;
 
function LetterAvailable(C: char): boolean;
{Check to see if letter is unused}
{Decrement count every time letter used}
var Inx: integer;
begin
Result:=False;
{Is it in the list?}
Inx:=SL.IndexOf(C);
{Exit if not}
if Inx<0 then exit;
{Decrement count each time a letter is used}
SL.Objects[Inx]:=Pointer(Integer(SL.Objects[Inx])-1);
if integer(SL.Objects[Inx])=0 then SL.Delete(Inx);
Result:=True;
end;
 
 
begin
SL:=TStringList.Create;
try
{Put letters in list and count number of available}
for I:=1 to Length(Secret) do
begin
{Already in list?}
Inx:=SL.IndexOf(Secret[I]);
{Store it with a count of 1, if not in list, otherwise, increment count}
if Inx<0 then SL.AddObject(Secret[I],Pointer(1))
else SL.Objects[Inx]:=Pointer(Integer(SL.Objects[Inx])+1);
end;
{Set all words to gray}
for I:=0 to High(Result) do Result[I]:=wcGrey;
{Test for exact position match}
for I:=1 to Length(Test) do
if Test[I]=Secret[I] then
begin
{If we haven't used up the letter, mark it green}
if LetterAvailable(Test[I]) then Result[I-1]:=wcGreen;
end;
{Test for non-positional match and mark them yellow}
for I:=1 to Length(Test) do
begin
{Check of letter available and not already green}
if LetterAvailable(Test[I]) then
if Result[I-1]<>wcGreen then Result[I-1]:=wcYellow;
end;
finally SL.Free; end;
end;
 
 
procedure ShowOneWordle(Memo: TMemo; Pair: TStringPair);
{Test one wordle pair and display result}
var S: string;
var I: integer;
var WA: TWordleArray;
begin
{Get color pattern}
WA:=TestWordle(Pair.Secret,Pair.Test);
{Generate text for color pattern}
S:='';
for I:=0 to High(WA) do
case WA[I] of
wcGreen: S:=S+' Green';
wcYellow: S:=S+' Yellow';
wcGrey: S:=S+' Gray';
end;
{Display pair and corresponding color pattern}
Memo.Lines.Add(Pair.Secret+' v '+Pair.Test+': '+S);
end;
 
 
procedure ShowWordleColors(Memo: TMemo);
{Show all test pairs}
var I: integer;
begin
for I:=0 to High(Pairs) do
ShowOneWordle(Memo,Pairs[I]);
end;
 
 
 
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY: Yellow Yellow Green Gray Gray
BULLY v LOLLY: Gray Gray Green Green Green
ROBIN v ALERT: Gray Gray Gray Yellow Gray
ROBIN v SONIC: Gray Green Yellow Green Gray
ROBIN v ROBIN: Green Green Green Green Green
 
Elapsed Time: 4.854 ms.
 
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
: color! ( c i -- ) tuck pad + c! here + 0 swap c! ;
 
: wordle ( a1 u1 a2 u2 -- a3 u3 )
2swap here swap move pad over erase dup 0 do
over i + c@ here i + c@ = if 2 i color! then
loop dup 0 do
2dup here swap rot i + 1 search nip nip if 1 i color! then
loop nip pad swap ;
 
:noname
create s" grey" , , s" yellow" , , s" green" , ,
does> swap 2* cells + 2@ type ; execute color.
 
: .wordle ( a1 u1 a2 u2 -- )
2over type ." v " 2dup type ." => " wordle
over + swap do i c@ color. space loop cr ;
 
:noname
0 s" ROBIN" 2dup 2dup s" SONIC" 2over s" ALERT"
s" BULLY" s" LOLLY" s" ALLOW" 2over
begin ?dup while .wordle repeat ; execute
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY => yellow yellow green grey grey
BULLY v LOLLY => grey grey green green green
ROBIN v ALERT => grey grey grey yellow grey
ROBIN v SONIC => grey green yellow green grey
ROBIN v ROBIN => green green green green green
</pre>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Function wordle(Byval respuesta As String, Byval supuesto As String) As String
Dim As Integer n, i, k
Dim As String resultado
Line 142 ⟶ 521:
End If
Next i
Sleep</langsyntaxhighlight>
{{out}}
<pre>ALLOW v LOLLY => [1, 1, 2, 0, 0] => yellow yellow green grey grey
Line 155 ⟶ 534:
BBAABBB: Expected 5 character target.</pre>
 
=={{header|FutureBasic}}==
This compact function returns a byte array (as a pstring) with 2, 1, 0, for matched, mismatched, unmatched. It is useful for games up to 15 chars wide, and is case sensitive as specified.
<syntaxhighlight lang="futurebasic">
short x = 80, y = 20
 
clear local fn colorString( w1 as str15, w2 as str15 ) as str15
str255 n : str15 c : c[0] = w2[0] : short r
for r = 1 to w1[0]
if w2[r] = w1[r] then c[r] = 2 else n[w1[r]]++
next
for r = 1 to w2[0]
if c[r] == 0 then if n[w2[r]] then n[w2[r]]-- : c[r] = 1
next
end fn = c
</syntaxhighlight>
This function uses the array to display output mimicking the appearance of WORDLE.
<syntaxhighlight lang="futurebasic">
mda(0) = {fn ColorDarkGray,fn ColorWithRGB(.7,.6,.3,1),fn ColorWithRGB(.3,.6,.3,1)}
void local fn wordleCompare( wordle as str15, guess as str15 )
str15 color : short r
color = fn colorString( wordle, guess )
text @"menlo bold", 14, fn colorLightGray
print %( 20, y ) wordle : text ,,fn colorWhite
for r = 1 to guess[0]
rect fill ( x, y, 24, 24 ), mda_object( color[r] )
print %( x + 7.5, y + 1 ) chr$( guess[r] ); : x += 28
next
x = 80 : y += 28
end fn
 
window 1, @"FB Wordle Compare", ( 0, 0, 265, 290 )
WindowSetBackgroundColor( 1, fn Colorblack )
fn wordleCompare( "ALLOW", "LOLLY" )
fn wordleCompare( "CHANT", "LATTE" )
fn wordleCompare( "ROBIN", "SONIC" )
fn wordleCompare( "PROUD", "LEAST" )
fn wordleCompare( "STEAL", "LEAST" )
fn wordleCompare( "LEAST", "LEAST" )
fn wordleCompare( "FULLY", "LABEL" )
fn wordleCompare( "We're", "She's" )
fn wordleCompare("LONGER", "STRING")
 
handleevents
</syntaxhighlight>
{{out}}
[[File:Wordle Comparison in FutureBasic.png]]
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 206 ⟶ 631:
fmt.Printf("%s v %s => %v => %v\n", pair[0], pair[1], res, res2)
}
}</langsyntaxhighlight>
 
{{out}}
Line 218 ⟶ 643:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (intercalate, mapAccumL)
import qualified Data.Map.Strict as M
Line 291 ⟶ 716:
color 2 = "green"
color 1 = "amber"
color _ = "gray"</langsyntaxhighlight>
{{Out}}
<pre>Target -> Guess -> Scores
Line 310 ⟶ 735:
Implementation (brute force):
 
<langsyntaxhighlight Jlang="j">wrdcmp=: {{
yw=.gr=. I.x=y
key=. '#' gr} x
Line 320 ⟶ 745:
end.
2 gr} 1 yw} (#y)#0
}}</langsyntaxhighlight>
 
A bit more efficient (about 3 times faster on task example, which might matter if a few microseconds was important):
 
<langsyntaxhighlight Jlang="j">wrdcmp=: {{
yw=. ;(] , ({.~1<.#)@-.)&.>/(<@I.y=/~x#~y~:x),<I.x=y
2 (I.x=y)} 1 yw} (#y)#0
Line 335 ⟶ 760:
assert 2 2 2 2 2-: 'robin' wrdcmp 'robin'
assert 0 0 2 1 0-: 'mamma' wrdcmp 'nomad'
assert 0 1 2 0 0-: 'nomad' wrdcmp 'mamma'</langsyntaxhighlight>
 
Explanation:
Line 347 ⟶ 772:
Task example:
 
<langsyntaxhighlight Jlang="j"> ('allow' wrdcmp 'lolly')&{&.;: 'gray yellow green'
yellow yellow green gray gray</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public final class WordleComparison {
 
public static void main(String[] args) {
List<TwoWords> pairs = List.of( new TwoWords("ALLOW", "LOLLY"), new TwoWords("ROBIN", "SONIC"),
new TwoWords("CHANT", "LATTE"), new TwoWords("We're", "She's"), new TwoWords("NOMAD", "MAMMA") );
for ( TwoWords pair : pairs ) {
System.out.println(pair.answer + " v " + pair.guess + " -> " + wordle(pair.answer, pair.guess));
}
}
private static List<Colour> wordle(String answer, String guess) {
final int guessLength = guess.length();
if ( answer.length() != guessLength ) {
throw new AssertionError("The two words must be of the same length.");
}
String answerCopy = answer;
List<Colour> result = Stream.generate( () -> Colour.GREY ).limit(guessLength).collect(Collectors.toList());
for ( int i = 0; i < guessLength; i++ ) {
if ( answer.charAt(i) == guess.charAt(i) ) {
answerCopy = answerCopy.substring(0, i) + NULL + answerCopy.substring(i + 1);
result.set(i, Colour.GREEN);
}
}
for ( int i = 0; i < guessLength; i++ ) {
int index = answerCopy.indexOf(guess.charAt(i));
if ( index >= 0 ) {
answerCopy = answerCopy.substring(0, index) + NULL + answerCopy.substring(index + 1);
result.set(i, Colour.YELLOW);
}
}
return result;
}
private enum Colour { GREEN, GREY, YELLOW }
private static record TwoWords(String answer, String guess) {}
private static final char NULL = '\0';
 
}
</syntaxhighlight>
{{ out }}
<pre>
ALLOW v LOLLY -> [YELLOW, YELLOW, GREEN, GREY, GREY]
ROBIN v SONIC -> [GREY, GREEN, YELLOW, GREEN, GREY]
CHANT v LATTE -> [GREY, YELLOW, YELLOW, GREY, GREY]
We're v She's -> [GREY, GREY, YELLOW, YELLOW, GREY]
NOMAD v MAMMA -> [GREY, YELLOW, GREEN, GREY, GREY]
</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 542 ⟶ 1,026:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>ALLOW -> LOLLY -> [1,1,2,0,0] -> amber amber green gray gray
Line 559 ⟶ 1,043:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq">def colors: ["grey", "yellow", "green"];
def wordle($answer; $guess):
Line 595 ⟶ 1,079:
| wordle(.[0]; .[1]) as $res
| ($res | map(colors[.])) as $res2
| "\(.[0]) v \(.[1]) => \($res) => \($res2)"</langsyntaxhighlight>
{{out}}
As for [[#Wren]].
Line 601 ⟶ 1,085:
=={{header|Julia}}==
{{trans|Wren}}
<langsyntaxhighlight lang="julia">const colors = ["grey", "yellow", "green"]
function wordle(answer, guess)
Line 635 ⟶ 1,119:
res2 = [colors[i + 1] for i in res]
println("$pair0 v $pair1 => $res => $res2")
end</langsyntaxhighlight>{{out}}
<pre>
ALLOW v LOLLY => [1, 1, 2, 0, 0] => ["yellow", "yellow", "green", "grey", "grey"]
Line 642 ⟶ 1,126:
ROBIN v SONIC => [0, 2, 1, 2, 0] => ["grey", "green", "yellow", "green", "grey"]
ROBIN v ROBIN => [2, 2, 2, 2, 2] => ["green", "green", "green", "green", "green"]
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="Kotlin">
fun main() {
val pairs = listOf(
TwoWords("ALLOW", "LOLLY"),
TwoWords("ROBIN", "SONIC"),
TwoWords("CHANT", "LATTE"),
TwoWords("We're", "She's"),
TwoWords("NOMAD", "MAMMA")
)
 
for (pair in pairs) {
println("${pair.answer} v ${pair.guess} -> ${wordle(pair.answer, pair.guess)}")
}
}
 
private fun wordle(answer: String, guess: String): List<Colour> {
val guessLength = guess.length
require(answer.length == guessLength) { "The two words must be of the same length." }
 
var answerCopy = answer
val result = MutableList(guessLength) { Colour.GREY }
for (i in guess.indices) {
if (answer[i] == guess[i]) {
answerCopy = answerCopy.substring(0, i) + NULL + answerCopy.substring(i + 1)
result[i] = Colour.GREEN
}
}
 
for (i in guess.indices) {
val index = answerCopy.indexOf(guess[i])
if (index >= 0) {
answerCopy = answerCopy.substring(0, index) + NULL + answerCopy.substring(index + 1)
if (result[i] != Colour.GREEN) {
result[i] = Colour.YELLOW
}
}
}
return result
}
 
private enum class Colour { GREEN, GREY, YELLOW }
 
private data class TwoWords(val answer: String, val guess: String)
 
private const val NULL = '\u0000'
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> [YELLOW, YELLOW, GREEN, GREY, GREY]
ROBIN v SONIC -> [GREY, GREEN, YELLOW, GREEN, GREY]
CHANT v LATTE -> [GREY, YELLOW, YELLOW, GREY, GREY]
We're v She's -> [GREY, GREY, YELLOW, YELLOW, GREY]
NOMAD v MAMMA -> [GREY, YELLOW, GREEN, GREY, GREY]
 
</pre>
 
=={{header|Nim}}==
{{trans|Wren}}
<syntaxhighlight lang="Nim">import std/[strformat, strutils]
 
type Color {.pure.} = enum Grey = "grey", Yellow = "yellow", Green = "green"
 
proc wordle(answer, guess: string): seq[Color] =
let n = guess.len
if answer.len != n:
quit "The words must be of the same length.", QuitFailure
var answer = answer
result.setLen(n)
for i in 0..<n:
if guess[i] == answer[i]:
answer[i] = '\0'
result[i] = Green
for i in 0..<n:
let ix = answer.find(guess[i])
if ix >= 0:
answer[ix] = '\0'
result[i] = Yellow
 
const Pairs = [["ALLOW", "LOLLY"],
["BULLY", "LOLLY"],
["ROBIN", "ALERT"],
["ROBIN", "SONIC"],
["ROBIN", "ROBIN"]]
 
for pair in Pairs:
let res = wordle(pair[0], pair[1])
echo &"""{pair[0]} v {pair[1]} → ({res.join(", ")})"""
</syntaxhighlight>
 
{{out}}
<pre>ALLOW v LOLLY → (yellow, yellow, green, grey, grey)
BULLY v LOLLY → (grey, grey, green, green, green)
ROBIN v ALERT → (grey, grey, grey, yellow, grey)
ROBIN v SONIC → (grey, green, yellow, green, grey)
ROBIN v ROBIN → (green, green, green, green, green)</pre>
 
=={{header|PARI/GP}}==
{{trans|Julia}}
<syntaxhighlight lang="PARI/GP">
colors = ["grey", "yellow", "green"];
 
wordle(answer, guess) =
{
n = #guess;
if (#answer != n, error("The words must be of the same length."));
answervector = Vecsmall(answer);
guessvector = Vecsmall(guess); \\ Convert guess to a vector of ASCII values
result = vector(n, i, 0);
for (i = 1, n,
if (guessvector[i] == answervector[i],
answervector[i] = 0;
result[i] = 2;
);
);
for (i = 1, n,
c = guessvector[i];
for (j = 1, n,
if (answervector[j] == c,
answervector[j] = 0;
result[i] = 1;
break;
);
);
);
result;
}
 
{
testpairs = [["ALLOW", "LOLLY"], ["BULLY", "LOLLY"], ["ROBIN", "ALERT"], ["ROBIN", "SONIC"], ["ROBIN", "ROBIN"]];
for (i = 1, #testpairs,
pair = testpairs[i];
res = wordle(pair[1], pair[2]);
res2 = vector(#res, j, colors[res[j] + 1]);
print(pair[1] " v " pair[2] " => " res " => " res2);
)
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY => [1, 1, 2, 0, 0] => ["yellow", "yellow", "green", "grey", "grey"]
BULLY v LOLLY => [0, 0, 2, 2, 2] => ["grey", "grey", "green", "green", "green"]
ROBIN v ALERT => [0, 0, 0, 1, 0] => ["grey", "grey", "grey", "yellow", "grey"]
ROBIN v SONIC => [0, 2, 1, 2, 0] => ["grey", "green", "yellow", "green", "grey"]
ROBIN v ROBIN => [2, 2, 2, 2, 2] => ["green", "green", "green", "green", "green"]
 
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Wordle_comparison
Line 658 ⟶ 1,291:
print "@$test => @{[ qw( green yellow grey )
[map ord, split //, s/.*\n//r =~ tr/\0\1/\2/cr] ]}\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 667 ⟶ 1,300:
ROBIN ROBIN => green green green green green
</pre>
 
Explanation (re-written to be more readable):
 
<syntaxhighlight lang="perl">
use strict;
use warnings;
 
sub show {
# print the given string, but convert certain non-printable characters to be visible:
# newline -> \n
# null \0 -> !
# control-A \1 -> ?
# control-B \2 -> _
local $_ = shift;
s/\n/\\n/g;
s/\0/!/g;
s/\01/?/g;
s/\02/_/g;
print "$_\n";
}
 
for my $test ( ["ALLOW", "LOLLY"],
["BULLY", "LOLLY"],
["ROBIN", "ALERT"],
["ROBIN", "SONIC"],
["ROBIN", "ROBIN"] )
{
print "-" x 80, "\n";
 
# @$test is two strings.
# my ($answer, $guess) = @$test
 
print "Start\n";
local $_ = join "\n", @$test;
show " '$_'";
 
show "Same letter, same position -> \0";
# For each letter in $answer that also appears in $guess, change the
# letter to a null character \0.
#
# [ -~] matches any letter (any printable character, not \0 or \n).
# Could also have used [A-Z]
#
# $` the substring before the matched letter
#
# tr!!.!cr
# !! the set of characters to transliterate (i.e., the empty set)
# c - complement the empty set (i.e., all characters)
# r - non-destructive: don't modify $` instead just return the resulting string
# !.! - change every character of $` to a dot '.'
# Could also have used "." x length($`)
#
# (??xxx) - use the result of the Perl expression xxx as a regex pattern,
# xxx will be some number of dots,
# one dot for every character before the matched letter.
# (A dot matches any character except newline \n.)
#
# \1 matches the same letter again.
# Results in something like s/(X)(.*\n...)X/\0$2\0/
#
# i.e., if letter X from $answer appears in the same position in $guess,
# then change X to a null character \0 in both $answer and $guess.
show " '$_'"
while s/([ -~])(.*\n(??{$` =~ tr!!.!cr}))\1/\0$2\0/;
 
show "Same letter, any position -> \1";
# [ -~] matches any remaining letter in $answer (again could have used [A-Z]).
#
# .*\n anything in $answer after the letter.
#
# .*?\1 anything in $guess up to (and including) that same letter.
# \1 matches whatever letter ([ -~]) matched.
# The ? causes us to select the left-most occurrence of the letter in
# $answer (in case there are multiple occurrences).
#
# Change that letter to control-A \01 in both $answer and $guess.
#
# i.e., if letter X from $answer appears anywhere in $guess, then change X
# to control-A in both $answer and $guess.
show " '$_'"
while s/([ -~])(.*\n.*?)\1/\01$2\01/;
 
print "Discard first word\n";
# s/.*\n//r
# r - non-destructive (return the result without modifying $_)
s/.*\n//;
show " '$_'";
 
show "Remaining letters -> \2";
# tr/\0\1/\2/cr
# /\0\1/ - the set of chars to transliterate: \0 null and \1 control-A
# c - complement the set of chars (i.e., any char that's not null or control-A)
# r - non-destructive
tr/\0\1/\2/c;
show " '$_'";
 
# In general: split //, "XYZ" - returns a list ("X", "Y", "Z").
# Here: split // - returns a string of chars all "\0" or "\1" or "\2".
my @chars = split //, $_;
show " @chars";
 
# Change "\0" to integer 0, "\1" to 1, "\2" to 2
my @indexes = map ord, @chars;
show " @indexes";
 
# Convert indexes 0-2 to color names.
my @colors = qw( green yellow grey );
print "@$test => @{ [ @colors[ @indexes ] ] }\n";
#print "@$test => @colors[ @indexes ]\n"; # same
}
</syntaxhighlight>
 
=={{header|Phix}}==
<small>Aside: You may be mildly surprised to see the 2nd for loop limit being clobbered like this, but you ''cannot'' change the limit mid-loop in Phix (an explicit exit would be far clearer) and hence you ''can'' do this.<br>
In practice the for loop takes a private copy of the value of the limit, be that n or more significantly say length(s), and ignores any changes you might subsequently make to it.</small>
<!--<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;">wordle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">answer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">)</span>
Line 705 ⟶ 1,449:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s v %s =&gt; %v =&gt; %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">answer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rac</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 714 ⟶ 1,458:
ROBIN v ROBIN => {2,2,2,2,2} => {"green","green","green","green","green"}
</pre>
 
=={{header|Picat}}==
My preferred representation of textual answer is:
* correct pos (green): Uppercase
* correct char (yellow): lowercase + "*"
* not in word (grey): lowercase
 
 
{{trans|Go}}
<syntaxhighlight lang="picat">main =>
Pairs = [["ALLOW", "LOLLY"],
["BULLY", "LOLLY"],
["ROBIN", "ALERT"],
["ROBIN", "SONIC"],
["ROBIN", "ROBIN"],
["ROBBY", "OBBYR"],
["ROSETTA", "OSSETAR"]],
foreach([Answer,Guess] in Pairs)
[Pres,Res] = wordle(Answer,Guess),
Len = Res.len,
printf("%w v %w => %w %w\n", Answer, Guess, Pres, Res)
end,
nl.
 
wordle(Answer,Guess) = [Presentation,Result =>
N = Guess.len,
Answer2 = copy_term(Answer), % don't touch Answer
if N != Answer.len then
print("The words must be of the same length.")
else
Result = new_list(N,grey), % grey by default
Presentation = copy_term(Guess).map(to_lowercase),
foreach(I in 1..N, Guess[I] == Answer2[I])
Answer2[I] := "",
Result[I] := green,
Presentation[I] := [to_uppercase(Guess[I])] ++ " "
end,
foreach(I in 1..N, Ix = find_first_of(Answer2,Guess[I]), Ix > 0)
Answer2[Ix] := "",
Result[I] := yellow,
Presentation[I] := [to_lowercase(Guess[I])] ++ "*"
end
end.</syntaxhighlight>
 
{{out}}
<pre>ALLOW v LOLLY => [l*,o*,L ,l ,y ] [yellow,yellow,green,grey,grey]
BULLY v LOLLY => [l ,o ,L ,L ,Y ] [grey,grey,green,green,green]
ROBIN v ALERT => [a ,l ,e ,r*,t ] [grey,grey,grey,yellow,grey]
ROBIN v SONIC => [s ,O ,n*,I ,c ] [grey,green,yellow,green,grey]
ROBIN v ROBIN => [R ,O ,B ,I ,N ] [green,green,green,green,green]
ROBBY v OBBYR => [o*,b*,B ,y*,r*] [yellow,yellow,green,yellow,yellow]
ROSETTA v OSSETAR => [o*,s ,S ,E ,t*,a*,r*] [yellow,grey,green,green,yellow,yellow,yellow]</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">'''Wordle comparison'''
 
from functools import reduce
Line 889 ⟶ 1,685:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Target -> Guess -> Scores
Line 906 ⟶ 1,702:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ tuck witheach
[ over i^ peek = while
2 rot i^ poke
Line 923 ⟶ 1,719:
$ "ROBIN" $ "SONIC" wordle-compare echo cr
$ "ROBIN" $ "ROBIN" wordle-compare echo cr
</syntaxhighlight>
</lang>
 
{{out}}
Line 938 ⟶ 1,734:
=={{header|Raku}}==
Updated to add a proof of concept matching for similarity where commonly found on spoofing domain names. Of course this is just the tip of the iceberg (only comparing results after decomposition) and there are way too many [https://util.unicode.org/UnicodeJsps/confusables.jsp Unicode homoglyphs] that can only be matched using a [http://www.unicode.org/Public/security/8.0.0/confusables.txt lookup table/database].
<syntaxhighlight lang="raku" perl6line># 20220216 Raku programming solution
 
sub wordle (\answer,\guess where [==] (answer,guess)».chars ) {
Line 968 ⟶ 1,764:
say .[0]~' vs '~.[1]~"\t"~ wordle .[0],.[1] for (
<ALLOW LOLLY>, <ROBIN ALERT>, <ROBIN SONIC>, <ROBIN ROBIN>, <BULLY LOLLY>,
<ADAPT SÅLÅD>, <Ukraine Ukraíne>, <BBAABBB BBBBBAA>, <BBAABBB AABBBAA> );</langsyntaxhighlight>
{{out}}
<pre>
Line 980 ⟶ 1,776:
BBAABBB vs BBBBBAA green green yellow yellow green yellow yellow
BBAABBB vs AABBBAA yellow yellow yellow yellow green grey grey
</pre>
 
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="Scala">
object WordleComparison extends App {
 
case class TwoWords(answer: String, guess: String)
enum Colour extends Enum[Colour] {
case GREEN, GREY, YELLOW
}
 
val pairs = List(TwoWords("ALLOW", "LOLLY"), TwoWords("ROBIN", "SONIC"),
TwoWords("CHANT", "LATTE"), TwoWords("We're", "She's"), TwoWords("NOMAD", "MAMMA"))
 
pairs.foreach(pair => println(s"${pair.answer} v ${pair.guess} -> ${wordle(pair.answer, pair.guess)}"))
 
def wordle(answer: String, guess: String): List[Colour] = {
if (answer.length != guess.length) {
throw new AssertionError("The two words must be of the same length.")
}
 
var answerCopy = answer
var result = List.fill(guess.length)(Colour.GREY)
 
for (i <- guess.indices) {
if (answer(i) == guess(i)) {
answerCopy = answerCopy.updated(i, NULL)
result = result.updated(i, Colour.GREEN)
}
}
 
for (i <- guess.indices) {
val index = answerCopy.indexOf(guess(i))
if (index >= 0 && result(i) != Colour.GREEN) {
answerCopy = answerCopy.updated(index, NULL)
result = result.updated(i, Colour.YELLOW)
}
}
result
}
 
val NULL = '\u0000'
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> List(YELLOW, YELLOW, GREEN, GREY, GREY)
ROBIN v SONIC -> List(GREY, GREEN, YELLOW, GREEN, GREY)
CHANT v LATTE -> List(GREY, YELLOW, YELLOW, GREY, GREY)
We're v She's -> List(GREY, GREY, YELLOW, YELLOW, GREY)
NOMAD v MAMMA -> List(GREY, YELLOW, GREEN, GREY, GREY)
 
</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">enum Colour : CustomStringConvertible {
case grey
case yellow
Line 1,028 ⟶ 1,877:
print("\(pair.0) v \(pair.1) => \(result)")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,040 ⟶ 1,889:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates wordle
sink removeFirst
Line 1,053 ⟶ 1,902:
otherwise $!
\) -> \[i](
when <'.' ?($@wordle <[<=$>]>)> do (yellow:$)! $ -> !removeFirst
when <'.'> do (grey:$)!
otherwise $!
\) !
Line 1,067 ⟶ 1,916:
 
['ALLOW', 'LOLLY'] -> wordle -> !OUT::write
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,074 ⟶ 1,923:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn wordle(answer string, guess string) []int {
n := guess.len
if n != answer.len {
Line 1,116 ⟶ 1,965:
println("${pair[0]} v ${pair[1]} => $res => $res2\n")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,129 ⟶ 1,978:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var colors = ["grey", "yellow", "green"]
 
var wordle = Fn.new { |answer, guess|
Line 1,163 ⟶ 2,012:
var res2 = res.map { |i| colors[i] }.toList
System.print("%(pair[0]) v %(pair[1]) => %(res) => %(res2)")
}</langsyntaxhighlight>
 
{{out}}
Line 1,175 ⟶ 2,024:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0;
 
proc ShowColors(Result);
Line 1,206 ⟶ 2,055:
ShowColors(Wordle("ROBIN", "SONIC"));
ShowColors(Wordle("ROBIN", "ROBIN"));
]</langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 2,068:
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Wordle_comparison
// by Galileo, 02/2022
 
Line 1,260 ⟶ 2,109:
print
next
</syntaxhighlight>
</lang>
{{out}}
<pre>ALLOW v LOLLY => yellow yellow green grey grey
9,476

edits