2

Define a function g with two arguments, w and n, where w a list of integers sorted in descending order ands n is an integer.; g should return a list produced by inserting n into w in a way that maintains descending order.

For example g[{9, 8, 5, 3, 2, 1}, 6] must return {9, 8, 6, 5, 3, 2, 1}.

How cam I do this in the best way in functional programming?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

2 Answers2

3

If Sort is not allowed then

Clear[g]

g[{i : _Integer ..}, n_Integer] :=
 {Cases[{i}, _?(# > n &)], n,
   Cases[{i}, _?(# < n &)]} // Flatten

g[{9, 8, 5, 3, 2, 1}, 6]

{9, 8, 6, 5, 3, 2, 1}

Or

Clear[g]

g[{i : _Integer ..}, n_Integer] :=

 Insert[SplitBy[{i}, # > n &], n, 2] // Flatten

g[{9, 8, 5, 3, 2, 1}, 6]

{9, 8, 6, 5, 3, 2, 1}

Or

Clear[g]

g[{i : _Integer ..}, 
  n_Integer] :=
 {i} /. {s___, u_?(# > n &), l_?(# < n &), e___} :>
   {s, u, n, l, e}

g[{9, 8, 5, 3, 2, 1}, 6]

{9, 8, 6, 5, 3, 2, 1}
Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
3

Here are three more ways to do it.

g[d_List, n_Integer] :=
  Flatten[Insert[SplitBy[d, n >= # &], {n}, 2]]

g[d_List, n_Integer] :=
  Flatten[Insert[GatherBy[d, n >= # &], {n}, 2]]

This next is just using Reap and Sow to do the gathering.

g[d_List, n_Integer] :=
  Flatten[Insert[Reap[If[# > n, Sow[#, 1], Sow[#, 2]] & /@ d][[2]], {n}, 2]]

For all of these

g[{9, 8, 5, 3, 2, 1}, 6]

gives

{9, 8, 6, 5, 3, 2, 1}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257