Home > OS >  Scala code returns false for 1012 > 977 and a few other values
Scala code returns false for 1012 > 977 and a few other values

Time:11-30

I have scala code and python code that are attempting the same task (2021 advent of code day 1 https://adventofcode.com/2021/day/1).

The Python returns the correct solution, the Scala does not. I ran diff on both of the outputs and have determined that my Scala code is incorrectly evaluating the following pairs:

1001 > 992 -> false
996 > 1007 -> true
1012 > 977 -> false

the following is my Python code:

import pandas as pd 

data = pd.read_csv("01_input.csv", header=None)

incr = 0
prevval = 99999

for index, row in data.iterrows():
    if index != 0:
        if row[0] > prevval:
            print(f"{index}-{row[0]}-{prevval}")
            incr  = 1
        prevval = row[0]

    prevval = row[0]
    

print(incr)

and here is my Scala code:

import scala.io.Source; // library to read input file in

object advent_of_code_2021_01 {
    def main(args: Array[String]): Unit = {

        val lines = Source.fromFile("01_input.csv").getLines().toList; // file as immutable list
        var increases = 0;

        for (i <- 1 until lines.length) { // iterate over list by index
            if (lines(i) > lines(i-1)) {
                increases  = 1;
                println(s"$i-${lines(i)}-${lines(i-1)}")
            }
        }

        println(increases);
    }
}

I do not understand what is causing this issue on these particular values. in the shell, Scala evaluates them correctly, but I do not know where to even begin with this. Is there some behavior I need to know about that I'm not accounting for? Am I just doing something stupid? Any help is appreciated, thank you.

CodePudding user response:

As @Edward Peters https://stackoverflow.com/users/6016064/edward-peters correctly identified, my problem was that I was doing string comparisons, and not numerical comparisons, so I needed to convert my values to Int and not String. I did this with the very simple .toInt and it fixed all my issues.

fixed scala code:

import scala.io.Source; // library to read input file in

object advent_of_code_2021_01 {
    def main(args: Array[String]): Unit = {

        val lines = Source.fromFile("01_input.csv").getLines().toList; // file as immutable list
        var increases = 0;

        for (i <- 1 until lines.length) { // iterate over list by index
            if (lines(i).toInt > lines(i-1).toInt) { // evaluate
                increases  = 1; // increment when true
                println(s"$i-${lines(i)}-${lines(i-1)}") // debug line
            }
        }

        println(increases); // result
    }
}
  • Related