Bookmark this: tool.io/online-algorithm/ski-rental/source-code
Online Ski-Rental Algorithm Demonstrator Source Code
Browse the implementation files for Online Ski-Rental Algorithm Demonstrator.tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';
import { parseInteger } from '../../parse/integer/tool';
export const demonstrateSkiRental = (
rentalCostInput: unknown,
purchaseCostInput: unknown,
usageDaysInput: unknown
): string => {
const rentalCost = parseFiniteNumber(rentalCostInput);
const purchaseCost = parseFiniteNumber(purchaseCostInput);
const usageDays = parseInteger(usageDaysInput);
if (
rentalCost === null ||
rentalCost <= 0 ||
purchaseCost === null ||
purchaseCost <= 0 ||
usageDays === null ||
usageDays < 0
)
return '';
const purchaseDay = Math.ceil(purchaseCost / rentalCost);
const onlineCost =
usageDays < purchaseDay
? usageDays * rentalCost
: (purchaseDay - 1) * rentalCost + purchaseCost;
const optimalCost = Math.min(
usageDays * rentalCost,
purchaseCost
);
return JSON.stringify(
{
competitiveRatio:
optimalCost === 0
? 1
: Number((onlineCost / optimalCost).toPrecision(12)),
decision:
usageDays < purchaseDay
? 'rent'
: `buy on day ${purchaseDay}`,
onlineCost,
optimalCost,
purchaseDay
},
null,
2
);
};
export const Tool: TypeTool = {
name: 'Online Ski-Rental Algorithm Demonstrator',
slug: 'online-algorithm/ski-rental',
intro:
'Compare a deterministic online rent-or-buy strategy with the optimal decision made in hindsight.',
tool: demonstrateSkiRental,
i: [
{
example: '10',
label: 'Rental Cost per Day',
placeholder: 'Positive daily cost',
type: 'number'
},
{
example: '100',
label: 'Purchase Cost',
placeholder: 'Positive purchase cost',
type: 'number'
},
{
example: '15',
label: 'Usage Days',
placeholder: 'Nonnegative whole days',
type: 'number'
}
],
o: [
{
example: '{ "onlineCost": 190 }',
label: 'Online Decision',
placeholder:
'Decision and competitive cost will appear here...',
render: 'textarea',
type: 'text'
}
],
cite: [
{
title: 'Ski rental problem - Wikipedia',
url: 'https://en.wikipedia.org/wiki/Ski_rental_problem'
}
]
};
export default Tool;
Description
Browse the implementation files for Online Ski-Rental Algorithm Demonstrator.