search
HomeBackend DevelopmentGolangData Transformations: Third Maximum and Jumbled Letters

Data Transformations: Third Maximum and Jumbled Letters

In this article, we will address two engaging tasks from the Perl Weekly Challenge #289: finding the third distinct maximum in an array and scrambling the letters of words in a text while keeping the first and last letters in place. We'll implement solutions in both Perl and Go.

Table of Contents

  1. Third Maximum
  2. Jumbled Letters
  3. Conclusion

Third Maximum

The first task involves finding the third distinct maximum in a given array of integers. If the third maximum doesn't exist, the function should return the maximum number.

Task Description

Input: An array of integers, @ints.

Output: The third distinct maximum or the maximum number if the third maximum doesn't exist.

Examples

  • Input: @ints = (5, 6, 4, 1)
    Output: 4
    (The distinct maximums are 6, 5, and 4.)

  • Input: @ints = (4, 5)
    Output: 5
    (The third maximum doesn't exist.)

  • Input: @ints = (1, 2, 2, 3)
    Output: 1
    (The distinct maximums are 3, 2, and 1.)

Solution

Perl Implementation

In this implementation, we create a set of unique values and then sort them in descending order to easily find the third maximum.


sub third_maximum {
    my @ints = @_;

    my %unique = map { $_ => 1 } @ints;
    my @distinct = sort { $b  $a } keys %unique;

    return @distinct >= 3 ? $distinct[2] : $distinct[0];
}


Go Implementation

The Go implementation follows a similar logic, using a map to capture unique integers and then sorting them.


func thirdMax(ints []int) (int, error) {
    if len(ints) == 0 {
        return 0, errors.New("input slice is empty")
    }

    unique := make(map[int]struct{})
    for _, num := range ints {
        unique[num] = struct{}{}
    }

    numsSorted := make([]int, 0, len(unique))
    for num := range unique {
        numsSorted = append(numsSorted, num)
    }

    sort.Slice(numsSorted, func(i, j int) bool {
        return numsSorted[i] > numsSorted[j]
    })

    if len(numsSorted) >= 3 {
        return numsSorted[2], nil
    }
    return numsSorted[0], nil
}


.

Jumbled Letters

The second task involves scrambling the letters of each word in a given text while ensuring that the first and last letters remain in place. Whitespace and punctuation should also be preserved.

Task Description

Input: A text string.

Output: A jumbled version of the input text.

Examples

  • Input: "According to a research at Cambridge University, it doesn't matter in what order the letters in a word are."
  • Output: (e.g.) "Acordnig to a reserach at Cmbraidge Uinversity, it dsoen't mtater in waht oder the ltteers in a wrod are." (The letters in each word are randomly rearranged, with the first and last letters unchanged.)

Solution

Perl Implementation

For this task, we define two functions:

  1. jumble_word: This function takes a word as input and scrambles the letters in the middle, while keeping the first and last letters intact. If the word is 3 letters or fewer, it is returned unchanged. For shuffling he letters we use Perl's List::Util module.
  2. jumble_text: This function processes a full text string, splitting it into words while preserving whitespace and punctuation. It applies the jumble_word function to each word, ensuring that only the words are scrambled.

use List::Util 'shuffle';

sub jumble_word {
    my ($word) = @_;

    return $word if length($word) 

<p>.</p>

<h4>
  
  
  Go Implementation
</h4>

<p>The Go implementation adopts a similar approach, utilizing the math/rand package for shuffling the letters,</p>

<pre class="brush:php;toolbar:false">

package main

import (
    "math/rand"
    "regexp"
    "strings"
    "time"
)

func jumbleWord(word string) string {
    if len(word) 

<p>.</p>

<h2>
  
  
  Conclusion
</h2>

<p>In this article, we explored two fun coding challenges: finding the third distinct maximum in an array and scrambling letters in a text. These tasks illustrate how different programming languages approach similar problems, each with its own strengths and methodologies. I hope these examples inspire you to tackle similar challenges and explore the capabilities of Perl and Go further!</p>

<p>You can find the complete code, including tests, on GitHub.</p>


          

            
        

The above is the detailed content of Data Transformations: Third Maximum and Jumbled Letters. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools