RogerBW's Blog

The Weekly Challenge 180: Unique Trim 30 August 2022

I’ve been doing the Weekly Challenges. The latest involved filtering strings and lists. (Note that this is open until 4 September 2022.)

Task 1: First Unique Character

You are given a string, $s.

Write a script to find out the first unique character in the given string and print its index (0-based).

My approach here is to iterate twice: the first pass builds up a character count and the second looks for the first character with a count of 1. (Another approach would involve a linked list to let a first-unique-character counter fall through the string as counts got too high, but I think this is clearer.)

Raku is typical:

sub firstunique($s) {

Split the string to individual characters.

    my @s = $s.comb;

Built a hash mapping character to count.

    my %cc;
    map {%cc{$_}++}, @s;

Go through the string character by character, until we find one with a count of 1.

    for 0..@s.end -> $i {
        if (%cc{@s[$i]} == 1) {
            return $i;

If we didn't, return -1 (this is outside the spec but clearly possible if there are no unique characters).

    return -1;

Many of the languages have an "enumerate" style function that lets one get both array member and index in a single looping construct; most don't autovivify default hash entries, though several have some way of specifying that for this hash the default value is that.

Task 2: Trim List

You are given list of numbers, @n and an integer $i.

Write a script to trim the given list where element is less than or equal to the given integer.

This sort of thing is a core function in everything except Lua and PostScript (and I wrote it for PostScript): in Perl and Raku it's grep, in Ruby it's find_all, and everywhere else it's filter. So the Ruby:

def trimlist(n, i)
  return n.find_all {|x| x > i}

is functionally the same as the JavaScript,

function trimlist(n, i) {
    return n.filter(e => e > i);

the same as the Perl,

sub trimlist($n, $i) {
  return [grep {$_ > $i} @{$n}];

and the same as the Rust (with a bit more complication).

fn trimlist(n: Vec<i64>, i: i64) -> Vec<i64> {
    n.into_iter().filter(|&x| x > i).collect::<Vec<i64>>()

(Rust also has retain which modifies a vector in place.)

Full code on github.

  1. Posted by Humberto Massa at 05:41pm on 30 August 2022

    The first one can be obtained with a simple regex:

    m/(.) {} :my $c = $0; /.[0]*-1).head.say

  2. Posted by RogerBW at 05:46pm on 30 August 2022

    True. I don't really love combining code into a regexp like this, but it gets the job done.

    (I've put code-markers round the code in your comment - if you want to do the same in future, use back-quotes as in standard markdown.)

  3. Posted by Humberto Massa at 01:42pm on 01 September 2022

    The solution above was actually wrong (it didn't account for the fact that $0 could be the second occurence of some character).

    I like the regex solution because, well, the problem is one in the domain of text processing...

    The corrected solution is raku m/:my %visited; . :my $c = $¢ <!{ %visited{$c++} }> <!before .* $c>/.&{ .pos // 0 - 1 }

    (did I do the markup correctly this time?)

  4. Posted by RogerBW at 01:47pm on 01 September 2022

    I'm a great fan of regexps – but even I will admit that they can make things hard to debug.

    (I added a test case "aabbcc" for no unique characters.)

    One of the things I've noticed as a result of solving the Weekly Challenges in other languages is just how much Perl relies on hashes and regexps as a sort of universal solution - it's rare for me to write a program without one or the other. Other languages tend to do these things in different ways.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1