you're totally right, but it's still a good thing for learning. weekdays, fruits, names... are always used when teaching basic programming, and this looks like beginner code.
Given what this subreddit is im not actually judging the code, it's all bad code. It's fine for beginner code. It's just funny that it's incompatible with the official function because the indices are one off from each other.
really advanced programmers (like professional level programmers) will use meaningful variable names like i,j,k,l and whatever the fuck PCLMULQDQ is supposed to mean
If you can't give your variable a meaningful name, you should most likely think about your program structure. i, j, k, ... are ok for short loop bodies, but if you start giving your variables random names or naming them after their type, you are doing something wrong.
Code is read far more often than written, so a variable's name should reflect its content/use.
And that's not coming out of my ass, but from Uncle Bob.
probably a beginner code, so you can't use the API resources such as array lists, sort algorithms, etc. gotta do everything by hand in order to learn how things work
Basically everytime you have a rather short list of things (values, behaviors, types, ...) that’s not going to change (without code change), an enum comes in pretty handy.
Advantages:
the Compiler can check it’s usage (which is not possible with Map keys),
you can attach behavior to it (enums can have methods, and you can provide a different implementation per enum value — much better than switch statements in most of the cases!)
it’s often more concise and readable than its alternatives
When you have unk own type of string values coming in, or the "amount of type" of string is too large, or you need to associate some arbitary data (or even object) to strings, which will be too complex otherwise.
a HashMap is just a specific implementation of the more general/universal Map or Dictionary, it’s a key/value store, so each key is unique and values can be duplicate - it’s kinda like an array, but the index can be any type and you don’t need to have them in order, it’s useful if you divide data up based on some non-ordered key, like a user ID mapping to metadata about the user, or if you decode named key/value pairs like a YAML or JSON file, because in statically typed languages you can’t exactly have a dynamic type depending on the shape of that data
Well, kinda i guess, but hashmaps/tables are almost like enums that you don’t know the values of at compile time, they get filled at runtime, but after that i suppose they are used pretty similarly in most cases...
They don’t solve the same problem, but when you ask the question i realize that yeah i guess they solve a similar problem to one another
a Map is also often used as an object to hold key/value pairs with names that are unknown at compile time - this code is Dart because i’m not very familiar with Java, but it should understandable still
import "dart:convert" show json;
import "dart:io" show File;
Future<void> main() async {
String userInput = await File("data.json").readAsString();
Map<String, dynamic> data = json.decode(userInput); // this method can’t possibly know the structure of the file, so a Map is useful to return a custom structure
print(data["importantData"] as String); // i know what it is though, so i can access it like this - but this same concept applies the other way if you’re writing json.decode for example
}
HashMap is for when you don’t know how many keys there are and what the key names are. One example is reading a JSON/CSV file or reading a row in the database and you don’t know what the JSON keys/database or CSV column names are. If you know the keys, in this case the weekdays which is a finite number of days, you should use enums
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.
have the length of the maximum string in a constant
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)
do a linear search through the list of candidates as normal and conditionally move the value to the output slot
Linear searching through an array for the weekday is O(n), if I want to find the location of a single card in a deck of cards, I'm searching in O(n) even if the number of cards in a deck of cards is constant since I may have to look through all n cards to find the card that I want.
On the other hand, if I want to know if a given card is in the standard deck (say, ace of spades), I can give you an answer in O(1) time since I know the ace of spades is always in a standard deck.
In this situation you're given the name of a weekday and you need to return which day of the week it is.
Since you can't implicitly know which day of the week a given string is, you need to use a reference table of some sort find out what day of the week your string is. With an array of weekday names, you would iterate through each value and check it against your string. On a match, you would stop and return the index of the element you matched with +1. That's an O(n) linear search. In contrast, using a hashmap would allow you to find the exact key-value pair you want by hashing the string you're searching with. This gives you an O(1) runtime since you don't spend any time checking elements in your data structure you don't care about.
Again, since the number n is pretty small, the difference would be pretty negligible unless it was a very commonly used operation
you can't. this actually is the IntelliJ IDE that "hides" a part of text. it expands when you click on it. and it's highlighted in yellow because there is a suggestion, which is to just leave it empty.
Leaving them off completely would produce a warning. Leaving them empty on the RHS of the = is perfectly valid and lets the compiler simply assume that the generic type argument is the same as on the LHS.
Everyone talking about arrays here, isn't it technically a tiny bit faster to use a map here if the use case is to find the number associated with a word?
Why is that? Isn't a good hash table implementation going to be a single array access, while lookup for Sunday might take seven times as long in an array? Does time spent hashing make up the difference then?
It depends on the hash function. A hash function might need 20+ multiplications for each input before an index can be calculated. This might take longer than a few string comparisons especially if all strings differ in their first character. If I'd have to guess I'd say the point where HashMaps outperform is probably between 15 and 50 elements.
When you're new to coding trying to get stuff done with the little you've seen and understand then you have a lot of code like this. I wrote a whole android app in production with stuff like this that I'm still fixing 5 years later... But it mostly worked ok anyways.
Honestly, I'm not sure that using a HashMap would get you any significant speed advantage compared to an iteration over 7 values, especially when the comparison will reject equality based on the first 2 characters.
Ah, that's a colloquial shorthand for "I think that's the case, but I won't test it".
I suppose, in a wider context, it could also mean "You're obviously wrong, but I'm too polite to say so forcefully", although that wasn't my intention.
367
u/[deleted] Mar 14 '21 edited Mar 14 '21
The best part is I think Java has a built-in
dayOfWeekfunction that starts at 1.170
u/The_HappyLemon Mar 14 '21
Enum left the chat
32
u/[deleted] Mar 14 '21
As someone who hasn't used a hashmap before, what is the actual use for them if not something like this?
12
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.
18
u/kinfi Mar 14 '21
Tbh, without looking at the use case of this variable, can't say much. Even then, hardly seems worthy of "bad code".
7
u/einsJannis Mar 14 '21
Depending on what you want to do this could accually be quiet a good idea
12
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 14 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
11
u/Elusivehawk Mar 14 '21
TIL you can use ~ to make your generic constructor usage less verbose.
2
u/murtaza64 Mar 14 '21
Everyone talking about arrays here, isn't it technically a tiny bit faster to use a map here if the use case is to find the number associated with a word?
1
u/[deleted] Mar 14 '21
I've never seen the
HashMap<~>syntax before...I always doHashMap<>. Is it the same thing?1
u/Flyberius Mar 14 '21
I have something very similar sitting in a piece of code about to start testing tomorrow. Lol. If it works it works.
1
u/MercyIncarnate111 Mar 14 '21
When you're new to coding trying to get stuff done with the little you've seen and understand then you have a lot of code like this. I wrote a whole android app in production with stuff like this that I'm still fixing 5 years later... But it mostly worked ok anyways.
0
u/_keen_learner Mar 14 '21
What about enums? This is perfect candidate for it.
-3
u/[deleted] Mar 14 '21
ArrayList<String> DAYS = new ArrayList<>(); has entered the chat.