How to resolve the algorithm Anagrams/Deranged anagrams step by step in the V (Vlang) programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Anagrams/Deranged anagrams step by step in the V (Vlang) programming language

Table of Contents

Problem Statement

Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with 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. Use the word list at unixdict to find and display the longest deranged anagram.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Anagrams/Deranged anagrams step by step in the V (Vlang) programming language

Source code in the v programming language

import os

fn deranged(a string, b string) bool {
	if a.len != b.len {
		return false
	}
	for i in 0..a.len {
		if a[i] == b[i] { return false }
	}
	return true
}
fn main(){
    words := os.read_lines('unixdict.txt')?
    
    mut m := map[string][]string{}
    mut best_len, mut w1, mut w2 := 0, '',''

    for w in words {
		// don't bother: too short to beat current record
		if w.len <= best_len { continue }
 
		// save strings in map, with sorted string as key
		mut letters := w.split('')
		letters.sort()
		k := letters.join("")
 
		if k !in m {
			m[k] = [w]
			continue
		}
 
		for c in m[k] {
			if deranged(w, c) {
				best_len, w1, w2 = w.len, c, w
				break
			}
		}
 
		m[k] << w
	}
 
	println('$w1 $w2: Length $best_len')
}

  

You may also check:How to resolve the algorithm Substring step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the PHP programming language
You may also check:How to resolve the algorithm Logical operations step by step in the Perl programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the Tcl programming language
You may also check:How to resolve the algorithm Shortest common supersequence step by step in the Factor programming language