1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-10-29 22:17:23 +01:00

feat(solutions): add offset-arrays/typescript/function

This commit is contained in:
Divlo 2021-06-29 19:27:11 +02:00
parent b9d99fb522
commit 0e6bca44b2
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
2 changed files with 91 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# offset-arrays/typescript/function
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.

View File

@ -0,0 +1,88 @@
import readline from 'readline'
const input: string[] = []
const readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout
})
readlineInterface.on('line', (value) => {
input.push(value)
})
readlineInterface.on('close', solution)
interface AssignmentValues {
[key: string]: number
}
interface Assignments {
[key: string]: AssignmentArray
}
class AssignmentArray {
public identifier: string
public firstIndex: number
public lastIndex: number
public values: AssignmentValues
constructor(assignment: string) {
const [identifier, rest] = assignment.split('[')
const [indexes, valuesString] = rest.split(']')
const [firstIndexString, lastIndexString] = indexes.split('..')
const firstIndex = parseInt(firstIndexString)
const lastIndex = parseInt(lastIndexString)
const [, numbersString] = valuesString.split('=')
const numbersStringArray = numbersString.trim().split(' ')
const numbers = numbersStringArray.map((number) => Number(number))
const values: AssignmentValues = {}
let index = 0
for (
let virtualIndex = firstIndex;
virtualIndex <= lastIndex;
virtualIndex++
) {
values[virtualIndex] = numbers[index]
index++
}
this.identifier = identifier
this.firstIndex = firstIndex
this.lastIndex = lastIndex
this.values = values
}
public getByIndex(index: number): number {
return this.values[index]
}
}
function solution(): void {
const assignments: Assignments = {}
const assignmentsLength = parseInt(input[0])
let assignmentIndex = 0
for (
assignmentIndex = 0;
assignmentIndex < assignmentsLength;
assignmentIndex++
) {
const assignment = input[assignmentIndex + 1]
const assignmentArray = new AssignmentArray(assignment)
assignments[assignmentArray.identifier] = assignmentArray
}
const operation = input[assignmentIndex + 1]
const [simplifiedOperation] = operation.split(']')
const nested = simplifiedOperation.split('[')
const lastOperationIndex = nested.length - 1
const operationIdentifiers = nested.slice(0, lastOperationIndex)
const operationIndex = parseInt(nested[lastOperationIndex])
let currentValue: number | null = null
for (let index = operationIdentifiers.length - 1; index >= 0; index--) {
const currentIdentifier = operationIdentifiers[index]
if (currentValue == null) {
currentValue = assignments[currentIdentifier].getByIndex(operationIndex)
} else {
currentValue = assignments[currentIdentifier].getByIndex(currentValue)
}
}
console.log(currentValue)
}