Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1 +1,2 @@
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum 0; thus if all elements are negative, the result must be the empty sequence.
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. <br>
An empty subsequence is considered to have the sum 0; thus if all elements are negative, the result must be the empty sequence.

View file

@ -0,0 +1,71 @@
(*
** This one is
** translated into ATS from the Ocaml entry
*)
(* ****** ****** *)
//
// How to compile:
// patscc -DATS_MEMALLOC_LIBC -o maxsubseq maxsubseq.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
typedef ints = List0(int)
(* ****** ****** *)
fun
maxsubseq
(xs: ints): (int, ints) = let
//
fun
loop
(
sum: int, seq: ints
, maxsum: int, maxseq: ints, xs: ints
) : (int, ints) =
(
case+ xs of
| nil () =>
(
maxsum
, list_vt2t(list_reverse(maxseq))
) (* end of [nil] *)
| cons (x, xs) => let
val sum = sum + x
and seq = cons (x, seq)
in
if sum < 0
then loop (0, nil, maxsum, maxseq, xs)
else (
if sum > maxsum
then loop (sum, seq, sum, seq, xs)
else loop (sum, seq, maxsum, maxseq, xs)
) (* end of [else] *)
end // end of [cons]
)
//
in
loop (0, nil, 0, nil, xs)
end // end of [maxsubseq]
implement
main0 () = () where
{
val
(maxsum
,maxseq) =
maxsubseq
(
$list{int}(~1,~2,3,5,6,~2,~1,4,~4,2,~1)
)
//
val () = println! ("maxsum = ", maxsum)
val () = println! ("maxseq = ", maxseq)
//
} (* end of [main0] *)

View file

@ -0,0 +1,45 @@
MODULE OvctGreatestSubsequentialSum;
IMPORT StdLog, Strings, Args;
PROCEDURE Gss(iseq: ARRAY OF INTEGER;OUT start, end, maxsum: INTEGER);
VAR
i,j,sum: INTEGER;
BEGIN
i := 0; maxsum := 0; start := 0; end := -1;
WHILE i < LEN(iseq) - 1 DO
sum := 0; j := i;
WHILE j < LEN(iseq) -1 DO
INC(sum ,iseq[j]);
IF sum > maxsum THEN
maxsum := sum;
start := i;
end := j
END;
INC(j);
END;
INC(i)
END
END Gss;
PROCEDURE Do*;
VAR
p: Args.Params;
iseq: POINTER TO ARRAY OF INTEGER;
i, res, start, end, sum: INTEGER;
BEGIN
Args.Get(p); (* Get Params *)
NEW(iseq,p.argc);
(* Transform params to INTEGERs *)
FOR i := 0 TO p.argc - 1 DO
Strings.StringToInt(p.args[i],iseq[i],res)
END;
Gss(iseq,start,end,sum);
StdLog.String("[");
FOR i := start TO end DO
StdLog.Int(iseq[i]);
IF i < end THEN StdLog.String(",") END
END;
StdLog.String("]=");StdLog.Int(sum);StdLog.Ln;
END Do;
END OvctGreatestSubsequentialSum.

View file

@ -1,9 +1,9 @@
import std.stdio;
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow {
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc {
int maxSum, thisSum, i, start, end = -1;
foreach (j, x; sequence) {
foreach (immutable j, immutable x; sequence) {
thisSum += x;
if (thisSum < 0) {
i = j + 1;
@ -23,8 +23,8 @@ inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow {
void main() {
const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
writeln("Maximal subsequence: ", maxSubseq(a1));
writeln("Maximal subsequence: ", a1.maxSubseq);
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
writeln("Maximal subsequence: ", maxSubseq(a2));
writeln("Maximal subsequence: ", a2.maxSubseq);
}

View file

@ -3,35 +3,29 @@ import std.stdio, std.algorithm, std.range, std.typecons;
mixin template InitsTails(T) {
T[] data;
size_t pos;
@property bool empty() pure nothrow {
@property bool empty() pure nothrow @nogc {
return pos > data.length;
}
void popFront() pure nothrow { pos++; }
void popFront() pure nothrow @nogc { pos++; }
}
struct Inits(T) {
mixin InitsTails!T;
@property T[] front() pure nothrow { return data[0 .. pos]; }
@property T[] front() pure nothrow @nogc { return data[0 .. pos]; }
}
auto inits(T)(T[] seq) { return seq.Inits!T; }
auto inits(T)(T[] seq) pure nothrow @nogc { return seq.Inits!T; }
struct Tails(T) {
mixin InitsTails!T;
@property T[] front() pure nothrow { return data[pos .. $]; }
@property T[] front() pure nothrow @nogc { return data[pos .. $]; }
}
auto tails(T)(T[] seq) pure nothrow { return seq.Tails!T; }
auto tails(T)(T[] seq) pure nothrow @nogc { return seq.Tails!T; }
T[] maxSubseq(T)(T[] seq) pure nothrow {
//return seq.tails.map!inits.join.reduce!(max!sum);
return reduce!max(tuple(0, T[].init),
seq
.tails
.map!inits
.join
.map!q{ tuple(a.sum, a) }
)[1];
T[] maxSubseq(T)(T[] seq) pure nothrow /*@nogc*/ {
//return seq.tails.map!inits.joiner.reduce!(max!sum);
return seq.tails.map!inits.join.minPos!q{ a.sum > b.sum }[0];
}
void main() {

View file

@ -0,0 +1,85 @@
MODULE GreatestSubsequentialSum;
IMPORT
Out,
Err,
IntStr,
ProgramArgs,
TextRider;
TYPE
IntSeq= POINTER TO ARRAY OF LONGINT;
PROCEDURE ShowUsage();
BEGIN
Out.String("Usage: GreatestSubsequentialSum {int}+");Out.Ln
END ShowUsage;
PROCEDURE Gss(iseq: IntSeq; VAR start, end, maxsum: LONGINT);
VAR
i, j, sum: LONGINT;
BEGIN
i := 0; maxsum := 0; start := 0; end := -1;
WHILE (i < LEN(iseq^)) DO
sum := 0; j := i;
WHILE (j < LEN(iseq^) - 1) DO
INC(sum,iseq[j]);
IF sum > maxsum THEN
maxsum := sum;
start := i;
end := j
END;
INC(j)
END;
INC(i)
END
END Gss;
PROCEDURE GetParams():IntSeq;
VAR
reader: TextRider.Reader;
iseq: IntSeq;
param: ARRAY 32 OF CHAR;
argc,i: LONGINT;
res: SHORTINT;
BEGIN
iseq := NIL;
reader := TextRider.ConnectReader(ProgramArgs.args);
IF reader # NIL THEN
argc := ProgramArgs.args.ArgNumber();
IF argc < 1 THEN
Err.String("There is no enough arguments.");Err.Ln;
ShowUsage;
HALT(0)
END;
reader.ReadLn; (* Skips program name *)
NEW(iseq,argc);
FOR i := 0 TO argc - 1 DO
reader.ReadLine(param);
IntStr.StrToInt(param,iseq[i],res);
END
END;
RETURN iseq
END GetParams;
PROCEDURE Do;
VAR
iseq: IntSeq;
start, end, sum, i: LONGINT;
BEGIN
iseq := GetParams();
Gss(iseq, start, end, sum);
i := start;
Out.String("[");
WHILE (i <= end) DO
Out.LongInt(iseq[i],0);
IF (i < end) THEN Out.Char(',') END;
INC(i)
END;
Out.String("]: ");Out.LongInt(sum,0);Out.Ln
END Do;
BEGIN
Do
END GreatestSubsequentialSum.

View file

@ -1,20 +1,14 @@
/*REXX program finds the shortest greatest continous subsequence sum.*/
arg @ /*get the arugment LIST (if any).*/
say 'words='words(@) ' list='@ /*show WORDS and LIST to console.*/
sum=word(@,1) /*a "starter" sum (of a sequence)*/
w=words(@) /*number of words in the list. */
at=1 /*where the sequence starts at. */
L=0 /*the length of the sequence. */
/*process the list. */
do j=1 for w; f=word(@,j)
do k=j to w; s=f
do m=j+1 to k
s=s+word(@,m)
end /*m*/
if s>sum then do; sum=s; at=j; L=k-j+1; end
end /*k*/
end /*j*/
/*REXX program finds the shortest greatest continuous subsequence sum.*/
parse arg @; w=words(@) /*get arg list; # words in list.*/
say 'words='w " list="@ /*show #words & LIST to console.*/
sum=0; L=0; at=w+1 /*default sum, length, starts at.*/
/* [↓] process the list of nums.*/
do j=1 for w; f=word(@,j) /*select one number at a time. */
do k=j to w /* [↓] process a sub─list of #s.*/
s=f; do m=j+1 to k; s=s+word(@,m); end /*m*/
if s>sum then do; sum=s; at=j; L=k-j+1; end
end /*k*/ /* [↑] chose greatest sum of #s.*/
end /*j*/
seq=subword(@,at,L); if seq=='' then seq="[NULL]"
say; say 'sum='word(sum 0,1)/1 " sequence="seq
/*stick a fork in it, we're done.*/
$=subword(@,at,L); if $=='' then $="[NULL]" /*Englishize it.*/
say; say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're done.*/

View file

@ -1,21 +1,14 @@
/*REXX program finds the longest greatest continous subsequence sum. */
arg @ /*get the arugment LIST (if any).*/
say 'words='words(@) ' list='@ /*show WORDS and LIST to console.*/
sum=word(@,1) /*a "starter" sum (of a sequence)*/
w=words(@) /*number of words in the list. */
at=1 /*where the sequence starts at. */
L=0 /*the length of the sequence. */
/*process the list. */
do j=1 for w; f=word(@,j)
do k=j to w; s=f
do m=j+1 to k
s=s+word(@,m)
end /*m*/
_=k-j+1
if (s==sum & _>L) | s>sum then do; sum=s; at=j; L=_; end
end /*k*/
end /*j*/
/*REXX program finds the longest greatest continuous subsequence sum.*/
parse arg @; w=words(@) /*get arg list; # words in list.*/
say 'words='w " list="@ /*show #words & LIST to console.*/
sum=0; L=0; at=w+1 /*default sum, length, starts at.*/
/* [↓] process the list of nums.*/
do j=1 for w; f=word(@,j) /*select one number at a time. */
do k=j to w; _=k-j+1 /* [↓] process a sub─list of #s.*/
s=f; do m=j+1 to k; s=s+word(@,m); end /*m*/
if (s==sum & _>L) | s>sum then do; sum=s; at=j; L=_; end
end /*k*/ /* [↑] chose longest greatest sum*/
end /*j*/
seq=subword(@,at,L); if seq=='' then seq="[NULL]"
say; say 'sum='word(sum 0,1)/1 " sequence="seq
/*stick a fork in it, we're done.*/
$=subword(@,at,L); if $=='' then $="[NULL]" /*Englishize it.*/
say; say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're done.*/

View file

@ -1,13 +1,9 @@
Infinity = 1.0/0
def subarray_sum(arr)
max, slice = -Infinity, []
arr.each_with_index do |n, i|
max, slice = 0, []
arr.each_index do |i|
(i...arr.length).each do |j|
sum = arr[i..j].inject(0) { |x, sum| sum += x }
if sum > max
max = sum
slice = arr[i..j]
end
sum = arr[i..j].inject(0, :+)
max, slice = sum, arr[i..j] if sum > max
end
end
[max, slice]

View file

@ -1,30 +1,8 @@
# the trick is that at any point
# in the iteration if starting a new chain is
# better than your current score with this element
# added to it, then do so.
# the interesting part is proving the math behind it
Infinity = 1.0/0
def subarray_sum(arr)
curr,max = -Infinity,-Infinity
first,last= 0,0
arr.each_with_index do |e,i|
curr = e + curr
if(e>curr)
curr = e
first=i
end
if(curr > max)
max = curr
last=i
end
end
return max,arr[first...last+1]
[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
[-1, -2, -3, -4, -5],
[]
].each do |input|
puts "\nInput seq: #{input}"
puts " Max sum: %d\n Subseq: %s" % subarray_sum(input)
end
input=[1,2,3,4,5,-8,-9,-20,40,25,-5]
p subarray_sum(input)
=>[65, [40, 25]]
input=[-3, -1]
p subarray_sum(input)
=>[-1, [-1]]

View file

@ -0,0 +1,22 @@
# the trick is that at any point
# in the iteration if starting a new chain is
# better than your current score with this element
# added to it, then do so.
# the interesting part is proving the math behind it
def subarray_sum(arr)
curr = max = 0
first, last, curr_first = arr.size, 0, 0
arr.each_with_index do |e,i|
curr += e
if e > curr
curr = e
curr_first = i
end
if curr > max
max = curr
first = curr_first
last = i
end
end
return max, arr[first..last]
end