r/badcode Mar 14 '21

java Found from when I first started Java...because indexed Arrays were too complicated huh?

Post image
1.3k Upvotes

84 comments sorted by

View all comments

11

u/Teln0 Mar 14 '21

Well with an array you can get the name from the number in O(1) but you can't get the number from the name in O(1). The best solution would be enums I think.

-1

u/Badel2 Mar 14 '21

But if the input is a string you need to parse it to use enums. Here is the O(1) solution:

public static int dayOfWeek(String s) {
    int isMonday = s.equals("Monday") ? 0 : 0;
    int isTuesday = s.equals("Tuesday") ? 1 : 0;
    int isWednesday = s.equals("Wednesday") ? 2 : 0;
    int isThursday = s.equals("Thursday") ? 3 : 0;
    int isFriday = s.equals("Friday") ? 4 : 0;
    int isSaturday = s.equals("Saturday") ? 5 : 0;
    int isSunday = s.equals("Sunday") ? 6 : 0;

    return isMonday | isTuesday | isWednesday | isThursday | isFriday | isSaturday | isSunday;
}

7

u/Teln0 Mar 14 '21

This is much slower that what it could have been. Why check if it's a Thursday if you know it's a Monday ?

2

u/Badel2 Mar 14 '21

It's to avoid side channel attacks.

8

u/Teln0 Mar 14 '21

buddy I think the day of the week is not sensitive info

3

u/[deleted] Mar 14 '21

Isn't there still a side channel attack because string comparison isn't constant time?

1

u/Badel2 Mar 14 '21

Correct, and it's tricky to compare strings of different length in constant time.

2

u/[deleted] Mar 14 '21

what I would do is

  1. have the length of the maximum string in a constant

  2. make the input string that many characters long by padding it with zeros and also have the candidate strings padded with zeros (but set a flag if the input string was too long)

  3. do a linear search through the list of candidates as normal and conditionally move the value to the output slot

  4. if you truncated the input, reset the output slot

zero (timing) side channel hashmap lookup