Anagrams/Deranged anagrams: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 5:
By analogy with [[Permutations/Derangements|derangements]] we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.
 
;Task
{{task heading}}
 
Use the word list at [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict] to find and display the longest deranged anagram.
 
 
{{task heading|;Related tasks}}
* [[Permutations/Derangements]]
* [[Best_shuffle|Best shuffle]]
Line 22:
=={{header|11l}}==
{{trans|Kotlin}}
<syntaxhighlight lang="11l">F is_not_deranged(s1, s2)
L(i) 0 .< s1.len
I s1[i] == s2[i]
Line 49:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program anaderan64.s */
Line 525:
=={{header|Ada}}==
{{Works with|Ada 2005}}
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Containers.Indefinite_Vectors;
Line 575:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} Uses the "read" PRAGMA of Algol 68 G to include the associative array code from the [[Associative_array/Iteration]] task.
<syntaxhighlight lang="algol68"># find the largest deranged anagrams in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
Line 708:
This can now return all the co-longest deranged anagrams when there are more than one. However it turns out that unixdict.txt only contains one. :)
 
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands!
-- Uses the customisable AppleScript-coded sort shown at <https://macscripter.net/viewtopic.php?pid=194430#p194430>.
-- It's assumed scripters will know how and where to install it as a library.
Line 800:
 
{{output}}
<syntaxhighlight lang="applescript">{{"excitation", "intoxicate"}}</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program anaderan.s */
Line 1,236:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">isDeranged?: function [p][
[a,b]: p
loop 0..dec size a 'i [
Line 1,276:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=Autohotkey"autohotkey">Time := A_TickCount
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetBatchLines -1
Line 1,339:
{{works with|GNU awk (gawk) 3.1.5}}
 
<syntaxhighlight lang="awk">#!/bin/gawk -f
BEGIN{
FS=""
Line 1,405:
 
Regular invocation would be:
<syntaxhighlight lang="sh">gawk -f deranged.awk /tmp/unixdict.txt</syntaxhighlight>
{{out}}
<pre>
Line 1,412:
 
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">DECLARE idx$ ASSOC STRING
 
FUNCTION Deranged(a$, b$)
Line 1,450:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Line 1,528:
Bracmat shuffles each new factor into place to keep the growing product normalized before continuing with the next word from the list.
The result is exactly the same, but the running time becomes much longer.
<syntaxhighlight lang="bracmat"> get$("unixdict.txt",STR):?wordList
& 1:?product
& :?unsorted
Line 1,595:
 
=={{header|C}}==
<syntaxhighlight lang=C"c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,716:
{{libheader|System.IO}}
{{works with|C sharp|6}}
<syntaxhighlight lang="csharp">public static void Main()
{
var lookupTable = File.ReadLines("unixdict.txt").ToLookup(line => AnagramKey(line));
Line 1,742:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <algorithm>
#include <fstream>
#include <functional>
Line 1,798:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">(->> (slurp "unixdict.txt") ; words
(re-seq #"\w+") ; |
(group-by sort) ; anagrams
Line 1,812:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
******************************************************************
* COBOL solution to Anagrams Deranged challange
Line 1,998:
=={{header|CoffeeScript}}==
This example was tested with node.js.
<syntaxhighlight lang="coffeescript">http = require 'http'
 
is_derangement = (word1, word2) ->
Line 2,044:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun read-words (file)
(with-open-file (stream file)
(loop with w = "" while w collect (setf w (read-line stream nil)))))
Line 2,070:
=={{header|D}}==
===Short Version===
<syntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.algorithm, std.string, std.array;
 
Line 2,090:
 
Using const(ubytes)[] instead of dstrings gives a runtime of about 0.07 seconds:
<syntaxhighlight lang="d"> string[][ubyte[]] anags;
foreach (const w; "unixdict.txt".readText.split)
anags[w.dup.representation.sort().release.assumeUnique] ~= w;</syntaxhighlight>
 
===Faster Version===
<syntaxhighlight lang="d">import std.stdio, std.file, std.algorithm, std.string, std.array,
std.functional, std.exception;
 
Line 2,132:
{{libheader| System.Classes}}
{{libheader| System.Diagnostics}}
<syntaxhighlight lang=Delphi"delphi">program Anagrams_Deranged;
 
{$APPTYPE CONSOLE}
Line 2,249:
=={{header|EchoLisp}}==
For a change, we use the french dictionary included in EchoLisp package.
<syntaxhighlight lang="scheme">(lib 'hash)
(lib 'struct)
(lib 'sql)
Line 2,282:
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="scheme">
(lib 'dico.fr.no-accent) ;; 209315 words into *words* table
(task)
Line 2,307:
 
=={{header|Eiffel}}==
<syntaxhighlight lang=Eiffel"eiffel">class
ANAGRAMS_DERANGED
 
Line 2,439:
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="elixir">defmodule Anagrams do
def deranged(fname) do
File.read!(fname)
Line 2,477:
=={{header|Erlang}}==
Using anagrams:fetch/2 from [[Anagrams]] and init_http/0 from [[Rosetta_Code/Find_unimplemented_tasks]]. Exporting words_from_url/1 to [[Ordered_words]].
<syntaxhighlight lang=Erlang"erlang">-module( anagrams_deranged ).
-export( [task/0, words_from_url/1] ).
 
Line 2,524:
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System;
 
let keyIsSortedWord = Seq.sort >> Seq.toArray >> String
Line 2,554:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: assocs fry io.encodings.utf8 io.files kernel math
math.combinatorics sequences sorting strings ;
IN: rosettacode.deranged-anagrams
Line 2,583:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type IndexedWord
Line 2,731:
=={{header|GAP}}==
Using function [[Anagrams#GAP|Anagrams]].
<syntaxhighlight lang="gap">IsDeranged := function(a, b)
local i, n;
for i in [1 .. Size(a)] do
Line 2,763:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
import (
"fmt"
Line 2,822:
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">def map = new TreeMap<Integer,Map<String,List<String>>>()
 
new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').eachLine { word ->
Line 2,857:
=={{header|Haskell}}==
If the longest deranged anagram includes three or more words we'll only print two of them. We also correctly handle duplicate words in the input.
<syntaxhighlight lang="haskell">{-# LANGUAGE TupleSections #-}
 
import Data.List (maximumBy, sort, unfoldr)
Line 2,906:
=={{header|Icon}} and {{header|Unicon}}==
This solution (which works in both languages) does a strict interpretation of the problem and ignores the fact that there may be multiple derangements that are the same length (including ignoring multiple derangements arising from the same set of words that are all anagrams).
<syntaxhighlight lang="unicon">link strings # for csort() procedure
 
procedure main()
Line 2,939:
=={{header|J}}==
This assumes that [http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt] has been saved in the current directory.
<syntaxhighlight lang="j"> #words=: 'b' freads 'unixdict.txt'
25104
#anagrams=: (#~ 1 < #@>) (</.~ /:~&>) words
Line 2,959:
=={{header|Java}}==
{{works with|Java|8}}
<syntaxhighlight lang="java">import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
Line 3,017:
brevity.
 
<syntaxhighlight lang=JavaScript"javascript">#!/usr/bin/env js
 
function main() {
Line 3,098:
=== Gecko ===
Word file is saved locally because browser won't fetch it cross-site. Tested on Gecko.
<syntaxhighlight lang="javascript"><html><head><title>Intoxication</title></head>
<body><pre id='x'></pre>
<script type="application/javascript">
Line 3,152:
This solution allows for the possibility of more than one answer.
 
<syntaxhighlight lang="jq"># Input: an array of strings
# Output: a stream of arrays
def anagrams:
Line 3,191:
=={{header|Julia}}==
 
<syntaxhighlight lang="julia">using Base.isless
# Let's define the less than operator for any two vectors that have the same type:
# This does lexicographic comparison, we use it on vectors of chars in this task.
Line 3,239:
 
=={{header|K}}==
<syntaxhighlight lang=K"k"> / anagram clusters
a:{x g@&1<#:'g:={x@<x}'x}@0:"unixdict.txt";
Line 3,248:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
import java.io.BufferedReader
Line 3,294:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">local(
anagrams = map,
words = include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt') -> split('\n'),
Line 3,351:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">print "Loading dictionary file."
open "unixdict.txt" for input as #1
a$=input$(#1,lof(#1))
Line 3,407:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">string.tacnoc = function(str) -- 'inverse' of table.concat
local arr={}
for ch in str:gmatch(".") do arr[#arr+1]=ch end
Line 3,447:
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">with(StringTools):
dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]):
L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]:
Line 3,458:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">words=First/@Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Table"];
anagramDegrangement=Function[{w1,w2},
Module[{c1=ToCharacterCode@w1,c2=ToCharacterCode@w2},
Line 3,470:
 
A similar approach using Mathematica 10:
<syntaxhighlight lang=Mathematica"mathematica">list = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Lines"];
MaximalBy[
Select[GatherBy[list, Sort@*Characters],
Line 3,482:
 
=={{header|Nim}}==
<syntaxhighlight lang=Nim"nim">import algorithm
import tables
import times
Line 3,529:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let sort_chars s =
let r = String.copy s in
for i = 0 to (String.length r) - 2 do
Line 3,599:
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">-- This assumes you've already downloaded the following file and placed it
-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt
 
Line 3,669:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">dict=readstr("unixdict.txt");
len=apply(s->#s, dict);
getLen(L)=my(v=List()); for(i=1,#dict, if(len[i]==L, listput(v, dict[i]))); Vec(v);
Line 3,684:
Using extra Stringlist for sorted by character words and insertion sort.<BR>
Runtime 153 ms -> 35 ms (Free Pascal Compiler version 3.3.1-r20:47268 [2020/11/02] for x86_64)
<syntaxhighlight lang="pascal">program Anagrams_Deranged;
{$IFDEF FPC}
{$MODE Delphi}
Line 3,810:
 
=={{header|Perl}}==
<syntaxhighlight lang=Perl"perl">sub deranged { # only anagrams ever get here
my @a = split('', shift); # split word into letters
my @b = split('', shift);
Line 3,852:
</pre>
===Alternate===
<syntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Line 3,872:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">deranged</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">word2</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: #000000;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word2</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">0</span>
Line 3,926:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
by Galileo, 06/2022 #/
 
Line 3,979:
 
=={{header|PHP}}==
<syntaxhighlight lang=PHP"php"><?php
$words = file(
'http://www.puzzlers.org/pub/wordlists/unixdict.txt',
Line 4,036:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">go =>
M = [W:W in read_file_lines("unixdict.txt")].group(sort),
Deranged = [Value : _Key=Value in M, Value.length > 1, allderanged(Value)],
Line 4,072:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(let Words NIL
(in "unixdict.txt"
(while (line)
Line 4,095:
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">function Test-Deranged ([string[]]$Strings)
{
$array1 = $Strings[0].ToCharArray()
Line 4,137:
=={{header|Prolog}}==
{{Works with|SWI Prolog}}
<syntaxhighlight lang=Prolog"prolog">longest_deranged_anagram :-
http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt',In,[]),
read_file(In, [], Out),
Line 4,202:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Structure anagram
word.s
letters.s
Line 4,344:
 
=={{header|Python}}==
<syntaxhighlight lang="python">import urllib.request
from collections import defaultdict
from itertools import combinations
Line 4,394:
 
Append the following to the previous code:
<syntaxhighlight lang="python">def most_deranged_ana(anagrams):
ordered_anagrams = sorted(anagrams.items(),
key=lambda x:(-len(x[0]), x[0]))
Line 4,443:
 
===Python: Faster Version===
<syntaxhighlight lang="python">from collections import defaultdict
from itertools import combinations
from pathlib import Path
Line 4,535:
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery"> [ over size over size != iff
[ 2drop false ] done
over sort over sort != iff
Line 4,564:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
 
longest.deranged.anagram <- function(dict=puzzlers.dict) {
Line 4,592:
{{out}}
 
<syntaxhighlight lang=R"r">> longest.deranged.anagram()
a b
3 excitation intoxicate</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(define word-list-file "data/unixdict.txt")
 
Line 4,647:
{{works with|Rakudo|2016.08}}
 
<syntaxhighlight lang=perl6"raku" line>my @anagrams = 'unixdict.txt'.IO.words
.map(*.comb.cache) # explode words into lists of characters
.classify(*.sort.join).values # group words with the same characters
Line 4,667:
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program finds the largest deranged word (within an identified dictionary). */
iFID= 'unixdict.txt'; words=0 /*input file ID; number of words so far*/
wL.=0 /*number of words of length L. so far*/
Line 4,716:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring"># Project : Anagrams/Deranged anagrams
 
load "stdlib.ring"
Line 4,801:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}
end
Line 4,829:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
dim theWord$(30000)
dim ssWord$(30000)
Line 4,880:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">//! Deranged anagrams
use std::cmp::Ordering;
use std::collections::HashMap;
Line 4,959:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object DerangedAnagrams {
 
/** Returns a map of anagrams keyed by the sorted characters */
Line 4,998:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme char)
(scheme cxr)
Line 5,054:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func find_deranged(Array a) {
for i in (^a) {
for j in (i+1 .. a.end) {
Line 5,093:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">! cim --memory-pool-size=512 deranged-anagrams.sim;
BEGIN
 
Line 5,232:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require http
 
Line 5,303:
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
 
Line 5,356:
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<syntaxhighlight lang="bash">function get_words {
typeset host=www.puzzlers.org
typeset page=/pub/wordlists/unixdict.txt
Line 5,408:
=={{header|Ursala}}==
This solution assumes the file <code>unixdict.txt</code> is passed to the compiler as a command line parameter.
<syntaxhighlight lang=Ursala"ursala">#import std
 
anagrams = |=tK33lrDSL2SL ~=&& ==+ ~~ -<&
Line 5,418:
main = leql$^&l deranged anagrams unixdict_dot_txt</syntaxhighlight>
The <code>anagrams</code> function is a little slow as defined above, but can be sped up by at least two orders of magnitude by grouping the words into classes of equal length, and sorting each word once in advance instead of each time a comparison is made as shown below.
<syntaxhighlight lang=Ursala"ursala">anagrams = @NSiXSlK2rSS *= ^(-<&,~&)*; |=rSStFtK33lrDSL2SL ~=@br&& ==@bl</syntaxhighlight>
We can speed it up by about another factor of 5 by starting from the group of longest words and stopping as soon as a deranged anagram is found instead of generating all anagrams.
<syntaxhighlight lang=Ursala"ursala">#import std
 
longest_deranged_anagram =
Line 5,437:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Sub Main_DerangedAnagrams()
Dim ListeWords() As String, Book As String, i As Long, j As Long, tempLen As Integer, MaxLen As Integer, tempStr As String, IsDeranged As Boolean, count As Integer, bAnag As Boolean
Dim t As Single
Line 5,496:
=={{header|Vlang}}==
{{trans|Go}}
<syntaxhighlight lang="vlang">import os
 
fn deranged(a string, b string) bool {
Line 5,547:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="ecmascript">import "io" for File
import "/sort" for Sort
 
Line 5,595:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">words:=Dictionary(25000); //-->Dictionary(sorted word:all anagrams, ...)
File("unixdict.txt").read().pump(Void,'wrap(w){
w=w.strip(); key:=w.sort(); words[key]=words.find(key,T).append(w);
Line 5,622:
</pre>
Replace the center section with the following for smaller code (3 lines shorter!) that is twice as slow:
<syntaxhighlight lang="zkl">nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...)
if(ws.len()>1){ // two or more anagrams
n:=ws[0].len(); // length of these anagrams
10,327

edits