* Generate examples. * * Each example consists of a question, e.g., '123+456' and and an * answer, e.g., '579'. * * @param digits Maximum number of digits of each operand of the * @param numExamples Number of examples to generate. * @param invert Whether to invert the strings in the question.
(digits, numExamples, invert)
| 118 | * @returns The generated examples. |
| 119 | */ |
| 120 | function generateData(digits, numExamples, invert) { |
| 121 | const digitArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; |
| 122 | const arraySize = digitArray.length; |
| 123 | |
| 124 | const output = []; |
| 125 | const maxLen = digits + 1 + digits; |
| 126 | |
| 127 | const f = () => { |
| 128 | let str = ''; |
| 129 | while (str.length < digits) { |
| 130 | const index = Math.floor(Math.random() * arraySize); |
| 131 | str += digitArray[index]; |
| 132 | } |
| 133 | return Number.parseInt(str); |
| 134 | }; |
| 135 | |
| 136 | const seen = new Set(); |
| 137 | while (output.length < numExamples) { |
| 138 | const a = f(); |
| 139 | const b = f(); |
| 140 | const sorted = b > a ? [a, b] : [b, a]; |
| 141 | const key = sorted[0] + '`' + sorted[1]; |
| 142 | if (seen.has(key)) { |
| 143 | continue; |
| 144 | } |
| 145 | seen.add(key); |
| 146 | |
| 147 | // Pad the data with spaces such that it is always maxLen. |
| 148 | const q = `${a}+${b}`; |
| 149 | const query = q + ' '.repeat(maxLen - q.length); |
| 150 | let ans = (a + b).toString(); |
| 151 | // Answer can be of maximum size `digits + 1`. |
| 152 | ans += ' '.repeat(digits + 1 - ans.length); |
| 153 | |
| 154 | if (invert) { |
| 155 | throw new Error('invert is not implemented yet'); |
| 156 | } |
| 157 | output.push([query, ans]); |
| 158 | } |
| 159 | return output; |
| 160 | } |
| 161 | |
| 162 | function convertDataToTensors(data, charTable, digits) { |
| 163 | const maxLen = digits + 1 + digits; |