Skip to content

Instantly share code, notes, and snippets.

@dinocarl
Created October 12, 2023 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinocarl/4d7611c7bf0ad6ec6487362638e90901 to your computer and use it in GitHub Desktop.
Save dinocarl/4d7611c7bf0ad6ec6487362638e90901 to your computer and use it in GitHub Desktop.
const S = f => g => x => f (x) (g (x));
const S2 = f => g => h => x => f (g (x)) (h (x));
// create a list based on a list of numbers that won't
// contain a zero, where the result is a list of products
// of the list without the number at the position of a given member
// eg [5,2,1,4,3] => [24, 60, 120, 30, 40]
// the key is that the computed product of the list and
// then divided by a given member, is equivalent to
// the product of the list without that member
// 5*2*1*4*3 = 120 / 5 = 24
// 2*1*4*3 = 24
const multAllWOIdxMem = compose(
map(apply(divide)),
apply(zip),
juxt([
compose(
apply(repeat),
juxt([
reduce(multiply, 1),
length
])
),
identity
])
);
// using the S combinators
const multAllWOIdxMem2 = compose(
// 3. apply the list of pairs one by one
// as arguments to the divide fn
map(apply(divide)),
S(
// 2. zip the repeated array with the original
// where the original member comes 2nd
flip(zip)
)(
// 1. get the length; compute the product of the list;
// fill an array with the result {length} times
S2(repeat)(reduce(multiply, 1))(length)
)
);
const data = [5,2,1,4,3];
// S(repeat)(length)(data)
// S2(repeat)(reduce(multiply, 1))(length)(data)
const result = multAllWOIdxMem2(data);
[
equals(result, [24, 60, 120, 30, 40]) ? 'passes' : 'fails',
result
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment