Untitled

mail@pastecode.io avatar
unknown
javascript
3 years ago
2.4 kB
2
Indexable
Never
class Vector2 {
  
    constructor (x = 0, y = 0) {
         this.x = x;
         this.y = y;
    }
}

class LightRay2 extends Vector2 {

    constructor (x = 0, y = 0, positiveXAxis = true, positiveYAxis = true) {
        super(x, y)
        this.positiveXAxis = positiveXAxis;
        this.positiveYAxis = positiveYAxis;
    }
        
    moveUp() {
        this.y = this.y + 1;
    }
    
    moveRight() {
        this.x = this.x + 1;
    }

    moveDown() {
        this.y = this.y - 1;
    }

    moveLeft() {
        this.x = this.x - 1;
    }

    moveX() {
        if (this.positiveXAxis) {
            this.moveRight();
        } else {
            this.moveLeft();
        }
    }

    moveY() {
        if (this.positiveYAxis) {
            this.moveUp();
        } else {
            this.moveDown();
        }
    }

    move() {
        this.moveX();
        this.moveY();
    }
}

function createCorners(xAxisMaximum = 0, yAxisMaximum = 0) {
    return [
        {x: 0, y: 0},
        {x: xAxisMaximum, y: 0},
        {x: 0, y: yAxisMaximum},
        {x: xAxisMaximum, y: yAxisMaximum}
    ]
}

function notInCorner(x = 0, y = 0, corners = [{x: 0, y: 0}]) {
    let output = true;

    for (let corner of corners) {
        if (corner.x === x && corner.y === y) {
            output = false;
            break;
        }
    }

    return output;
}
  
function reflections(xAxisMaximum, yAxisMaximum) {
    const corners = createCorners(xAxisMaximum, yAxisMaximum);
    const lightRay = new LightRay2(1,1);
    let output = false;

    console.log("corners: ", corners);
    console.log("lightRay: ", lightRay);

    while (notInCorner(lightRay.x, lightRay.y, corners)) {
        if (lightRay.x === xAxisMaximum || lightRay.x === 0) lightRay.positiveXAxis = !lightRay.positiveXAxis;
        if (lightRay.y === yAxisMaximum || lightRay.y === 0) lightRay.positiveYAxis = !lightRay.positiveYAxis;
        lightRay.move();
    }

    output = lightRay.x === 0 && lightRay.y === 0 || lightRay.x === xAxisMaximum && lightRay.y === yAxisMaximum;
    
    console.log("lightRay after: ", lightRay);
    console.log("output: ", output);

    return output;
}

reflections(10, 10);
reflections(10, 20);
reflections(12, 23);
reflections(5, 25);