minhajuddin

minhajuddin

I am using the code below to generate room ids:

reservations = [%{rooms: 1},
                %{rooms: 2},
                %{rooms: 3}]

{reservations_with_room_numbers, _} =
  Enum.reduce(reservations, {[], 0}, fn reservation, {acc, offset} ->
    upper_limit = offset+reservation.rooms - 1
  room_numbers = Enum.to_list(offset..upper_limit)
  reservation_with_room_numbers = Map.put(reservation, :room_numbers, room_numbers)
  {[reservation_with_room_numbers|acc], upper_limit + 1}
end)

IO.inspect Enum.reverse(reservations_with_room_numbers)
# =>
# [
# %{room_numbers: [0], rooms: 1}
# %{room_numbers: [1, 2], rooms: 2},
# %{room_numbers: [3, 4, 5], rooms: 3},
# ]

The code above seems too complicated for such a simple task, Is there a simpler way to do the same?

System.unique_integer [:monotonic, :positive] gives out unique integers starting at 1, However there is no way to reset it after the generation is done, so that it starts from 1 for the next call.

Showing Posts 1 to 10

andre1sk

andre1sk

Can be cleaned up a bit with functions something like:

def rwrn(reservations, start \\0, acc \\[])
def rwrn([],_,acc), do: Enum.reverse(acc)
def rwrn([%{rooms: rooms} | t], start, acc) do
  upto = start + rooms
  rwrn(t, upto, [%{rooms: rooms, room_numbers: Enum.to_list(start..upto - 1)} | acc])
end
minhajuddin

minhajuddin OP

Thanks this is definitely clearer than the first implementation :slight_smile:

This would be easy in javascript with a simple generator function. I was hoping there would be some generator function which keeps giving new ids.

var makeGenerator = function(offset){
  return function(){
    offset += 1;
    return offset;
  }
};

var generator = makeGenerator(0);

var reservations = [{rooms: 1}, {rooms: 2}, {rooms: 3}];
reservations.map(x => {
  x.room_numbers = _.times(x.rooms, x => generator())
  return x;
})

andre1sk

andre1sk

Stream.iterate(offset, &(&1+1)) ?

minhajuddin

minhajuddin OP

The js code persists the state, so it can give new ids, However this code gives a new set of ids starting from 0 every time.

s = Stream.iterate(0, &(&1+1))

IO.inspect Enum.take(s, 2) #=> [0, 1]
IO.inspect Enum.take(s, 2) #=> [0, 1]
JEG2

JEG2

Author of Designing Elixir Systems with OTP
defmodule RoomBuilder do
  def build([{:rooms, n} | rooms], built, next_id) do
    room_numbers =
      Stream.iterate(next_id, &(&1 + 1))
      |> Enum.take(n)
    build(rooms, [room_numbers | built], next_id + n)
  end
  def build([ ], built, _generator), do: Enum.reverse(built)
end

reservations = [rooms: 1, rooms: 2, rooms: 3]
RoomBuilder.build(reservations, [ ], 0)
|> IO.inspect
JEG2

JEG2

Author of Designing Elixir Systems with OTP

Or, with a generator:

defmodule Generator do
  def new(start) do
    Agent.start_link(fn -> start end)
  end

  def next(generator) do
    Agent.get_and_update(generator, fn value -> {value, value + 1} end)
  end
end

defmodule RoomBuilder do
  def build([{:rooms, n} | rooms], built, generator) do
    room_numbers =
      Stream.repeatedly(fn -> Generator.next(generator) end)
      |> Enum.take(n)
    build(rooms, [room_numbers | built], generator)
  end
  def build([ ], built, _generator), do: Enum.reverse(built)
end

{:ok, generator} = Generator.new(0)
reservations = [rooms: 1, rooms: 2, rooms: 3]
RoomBuilder.build(reservations, [ ], generator)
|> IO.inspect
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

One thing that isn’t clear is if we want a pure or impure solution. The original post had both. They’re wildly different solutions and people need to be aware of that.

minhajuddin

minhajuddin OP

Thanks for sharing this solution.

rvirding

rvirding

Creator of Erlang

I don’t quite understand how you mean starts again at 1. Documentation for :erlang.unique_interger, which I assume System.unique_integer calls, says:

“Generates and returns an integer unique on current runtime system instance. The integer is unique in the sense that this BIF, using the same set of modifiers, will not return the same integer more than once on the current runtime system instance.”

A simple test shows getting a different integer for each call.

minhajuddin

minhajuddin OP

Thanks for dropping in :slight_smile:

You are right about System.unique_integer, It gives a stream of increasing numbers. However, I want my ids to reset for every function call. So, something like below:

reservations = [%{rooms: 1},
                %{rooms: 4}]
assert make_reservation(rooms) == [%{rooms: 1, ids: [1]},
                %{rooms: 4, ids: [2, 3, 4, 5]}]
# and a subsequent call
reservations = [%{rooms: 2},
                %{rooms: 3}]
assert make_reservation(rooms) == [%{rooms: 1, ids: [1, 2]},
                %{rooms: 4, ids: [3, 4, 5]}]

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews