Published
Edited
Mar 23, 2019
Insert cell
Insert cell
function repeatedString(s, n) {

if (s === 'a') return n;
if (!s.includes('a')) return 0;
// How many 'a' are in the given string: 'aba' has 2 'a'
const ocurrences = s.match(/a/g).length;
// How may times does the string can be in a string of n: 10/3 = 3.33
const repeatTimes = n / s.length;
// Calculate how many chars from the remanent
const c = n - s.length * Math.floor(repeatTimes);
// Generate the string base from the chars that we need for the remanent
const remanentStr = s.substr(0, c).match(/a/g) || [];

// Check if the repeatTimes is not an integer we need to calculate the remanent
return Number.isInteger(repeatTimes)
? ocurrences * repeatTimes
: (ocurrences * Math.floor(repeatTimes)) + remanentStr.length;

}
Insert cell
repeatedString('gfcaaaecbg', 547602)
Insert cell
repeatedString('aba', 10)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more