Skip to content

Eliminating redundant choice points in ints_median_index/3 #2559

Answered by jjtolton
jjtolton asked this question in Q&A
Discussion options

You must be logged in to vote

Whoops... I was confusing the order of the arguments for nth1/3 🤦

:- use_module(library(lists)).
:- use_module(library(reif)).
:- use_module(library(debug)).
:- use_module(library(format)).

ints_median_index(Ints, Median, Index) :-
        length(Ints, N),
        Index #= N // 2,
        Index1 #= Index + 1,
        if_(clpz_t( (N mod 2) #= 0),
            (   nth1(Index, Ints, A),
                nth1(Index1, Ints, B),
                Median is (A + B) / 2
            ),
            nth1(Index1, Ints, Median)
           ).
        
        
?- ints_median_index([1, 2, 3], Median, Index).
%@    Median = 2, Index = 1.

?- ints_median_index([1, 2, 3, 4], Median, Index).
%@    Median = 2.5…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@jjtolton
Comment options

@jjtolton
Comment options

Answer selected by jjtolton
@triska
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants