stevensonmt

stevensonmt

As I continue working through Leetcode, I find a lot of problems that are not conducive to immutable data structures, such as sliding window problems using two pointers. What I have found is that I can usually circumvent this by using a reduce function to track any “mutable” variables. For instance this problem I solved in Rust with:

pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {
        let max = nums.len();
        let target: i32 = nums.iter().sum::<i32>() - x;
        if target == 0 {
            return max as i32
        }
        let mut i = 0;
        let mut sub_sum = 0;
        let mut max_len = 0;
        let mut found = false;
        for j in 0..max {
            sub_sum += nums[j];
            while i <= j && sub_sum > target {
                sub_sum -= nums[i];
                i += 1;
            }
            if sub_sum == target {
                found = true;
                max_len = max_len.max(j - i + 1);
            }
        }
        if found {
            (max - max_len) as i32
        } else {
            -1
        }
    }

You have to track the two pointers i and j as well as the sub_sum and max_len values. This implementation iterates over the end of the subarray with appropriate sum, but it could be implemented to iterate over the beginning. In either case you know the range of values to iterate over, which takes care of tracking one variable. To track the other 3 variables I used a 3 tuple accumulator in a reduce function like so:

defmodule Solution do
  @spec min_operations(nums :: [integer], x :: integer) :: integer
  def min_operations(nums, x) do
    max = Enum.count(nums)
    target = Enum.sum(nums) - x 
    if target == 0 do
      max
    else
      nums_arr = nums |> Enum.with_index() |> Map.new(fn {v, k} -> {k, v} end)
      max_len = 
        0..max - 1
        |> Enum.reduce({-1, 0, 0}, fn j, {ml, ss, i} ->
                          
                      {uml, uss, ui} = find_max_sub(nums_arr, i, j, ml, target, ss + nums_arr[j]) 
                        {max(uml, ml), uss, ui} 
                    end)
        |> elem(0)
      if max_len < 0 do
        max_len 
      else
        max - max_len
      end
    end
  end
  
      
  def find_max_sub(_nums, start, finish, max_len, target, sub_sum) when start > finish or sub_sum < target, do: {max_len, sub_sum, start}
  def find_max_sub(_, start, finish, max_len, target, target), do: {max(max_len, finish - start + 1), target, start}
  def find_max_sub(nums, start, finish, max_len, target, sub_sum) do
    find_max_sub(nums, start + 1, finish, max_len, target, sub_sum - nums[start])
  end
end

I have two questions:

  1. Is this an anti-pattern that should be avoided and if so, why?
  2. How can I implement this sort of algorithm in a more functional style?

Showing Posts 1 to 5

eksperimental

eksperimental

Definitely break it up into helper functions.calculate_max(nums, target), max_len(nums)

al2o3cr

al2o3cr

Using a tuple as an accumulator is a pretty common pattern; past 4 or 5 elements it might be time to use a map or a struct instead.

Using the accumulator to carry state between iterations is a really common pattern - for instance, it’s the whole idea behind Stream.transform/3.

stevensonmt

stevensonmt OP

Do you mean something like this:

defmodule Solution do
  @spec min_operations(nums :: [integer], x :: integer) :: integer
  def min_operations(nums, x) do
    target = Enum.sum(nums) - x 
    max = Enum.count(nums)
    find_min_ops(nums, target, max)
  end
  
  def find_min_ops(_, 0, max), do: max
  def find_min_ops(nums, target, max) do
    nums
    |> Enum.with_index()
    |> Map.new(fn {v, k} -> {k, v} end)
    |> max_len(target, max)
    |> min_ops(max)
  end
      
  def max_len(nums_arr, target, max) do
    0..max - 1
    |> Enum.reduce({-1, 0, 0}, fn j, {ml, ss, i} ->
                      {uml, uss, ui} = find_max_sub(nums_arr, i, j, ml, target, ss + nums_arr[j]) 
                      {max(uml, ml), uss, ui} 
                    end)
    |> elem(0)
  end
      
  def min_ops(max_sub_len, _) when max_sub_len < 0, do: max_sub_len
  def min_ops(max_sub_len, max), do: max - max_sub_len
      
  def find_max_sub(_nums, start, finish, max_len, target, sub_sum) when start > finish or sub_sum < target, do: {max_len, sub_sum, start}
  def find_max_sub(_, start, finish, max_len, target, target), do: {max(max_len, finish - start + 1), target, start}
  def find_max_sub(nums, start, finish, max_len, target, sub_sum) do
    find_max_sub(nums, start + 1, finish, max_len, target, sub_sum - nums[start])
  end
end
eksperimental

eksperimental

Yes, exactly like that.
min_operations is the only public function, the rest you can use defp in order to make them private.

cjbottaro

cjbottaro

One thing that I have always loved about Elixir is that it favors practicality.

If your reduce function’s aggregator is huge and cumbersome, consider just making an :ets table for the duration of the function. Basically gives you the mutability that you’re used to, and if you have a decent after clause, then you won’t memory leak.

:hugs:

But over time, you should get really comfortable with Enum.reduce and a map accumulator. Or just recursive functions as above.

— All posts loaded —

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 92995 915
New
caslu
I want to open this thread for you all to discuss and help those who really like Ash but are still hesitant to use it in a real project. ...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
GES233
I’m posting this in response to Jose’s recent tweet (Cr. link) : People are sleeping on Elixir for a coding harness: Hot-code swappi...
New
_mfierro
Hello, I wrote Stop My Hand, a Scattergories-like web application using Phoenix/LiveView as my learning project for Elixir (after readin...
New
marciol
It would be helpful to have a list of companies worldwide that hire engineers without prior experience in Elixir. Often, it can be quite ...
New
durvia
Anyone running long-lived stateful processes on BEAM? We’re building an AI agent runtime and would love to compare notes. We’re a small ...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews