Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #43697

Re: Find combinations with the right sum

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.forth
Subject Re: Find combinations with the right sum
Date 2015-11-24 06:22 +0000
Organization A noiseless patient Spider
Message-ID <n30vmf$er5$1@dont-email.me> (permalink)
References <n2t4ju$ald$1@dont-email.me>

Show all headers | View raw


WJ wrote:

> Ruby:
> 
> def combinations_summing_to sum,len,numbers
>   numbers.to_a.combination(len).select{|xs| xs.reduce(:+) == sum}
> end
> 
> combinations_summing_to 45,4,(9..22)
>     ===>[[9, 10, 11, 15], [9, 10, 12, 14], [9, 11, 12, 13]]
> 
> combinations_summing_to 20,3,[2,3,5,7,8,9]
>     ===>[[3, 8, 9], [5, 7, 8]]
> 
> One would imagine that this would be painfully difficult in
> ANS Forth, wouldn't he?

Ocaml:

(* All combinations of size m from a list. *)
let rec  combins m list =
  if 1 = m then
    List.map (fun x -> [x]) list
  else
    let rec  go = function
        [x] -> []
      | x::xs -> (List.map ((@) [x]) (combins (m-1) xs)) @ (go xs)
    in go list ;;

let combinations_summing_to sum len integers =
  integers |> combins len |>
    List.filter (fun list -> sum = List.fold_left (+) 0 list) ;;

combinations_summing_to 20 3 [2;3;5;7;8;9];;
 ===>
[[3; 8; 9]; [5; 7; 8]]

combinations_summing_to 20 3 [2;3;4;5;6;7;8;9;10];;
 ===>
[[2; 8; 10]; [3; 7; 10]; [3; 8; 9]; [4; 6; 10]; [4; 7; 9]; [5; 6; 9];
 [5; 7; 8]]

Back to comp.lang.forth | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Find combinations with the right sum "WJ" <w_a_x_man@yahoo.com> - 2015-11-22 19:21 +0000
  Re: Find combinations with the right sum foxaudioresearch@gmail.com - 2015-11-22 14:46 -0800
    Re: Find combinations with the right sum Chris Curl <ccurl609@gmail.com> - 2015-11-22 16:48 -0800
    Re: Find combinations with the right sum Chris Curl <ccurl609@gmail.com> - 2015-11-22 16:49 -0800
    Re: Find combinations with the right sum Ron Aaron <rambamist@gmail.com> - 2015-11-23 07:27 +0200
      Re: Find combinations with the right sum Alfred Singlestone <vitonis@gmail.com> - 2015-11-23 15:45 -0800
  Re: Find combinations with the right sum "WJ" <w_a_x_man@yahoo.com> - 2015-11-24 06:22 +0000

csiph-web