NerdLounge
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Forum Help: Calling Other Programmers!

5 posters

Go down

Forum Help: Calling Other Programmers!  Empty Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 2:11 pm

Hey guys! I'm putting out an SOS to other programmers lurking here on the forum. I desperately need some advice on homework I'm doing, just someone I can bounce some ideas off of. I'm happy to exchange sewing lessons or paper-editing in return!

I'm trying to write a Java program that would track the location and distance of jogs. So, at Location A, you ran Distance X and Distance Z. At Location B, you ran Distance Y. I then need to print out the locations and the fastest time for that location. The homework stipulates I need to store it in one data structure, and not in individual variables.

My original idea was to have 2 LinkedLists; one for location, one for distance. Works fantastic. I could also stick all of them into one LinkedList, and then just iterate over the LinkedList to print them out. However, I have no idea how to get the "fastest" value for each location. I was thinking of using a HashMap; I could iterate over the Location LinkedList, and if the HashMap doesn't contain the location, add it. But how do I keep the location "tied" to the distance?

Am I missing something really obvious? Sorry for the stupid question...
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 3:33 pm

I'm a little confused about using the term "fastest" when it looks like you are storing distances but not times.

I'm also not sure why you want LinkedLists. A sorted heap (or sorted list) seems more efficient for this task. (One heap/list per location, and a HashMap to give you those lists, using the Location as the key.)

Been a while since I touched Java, though; is it already easy to keep a LinkedList sorted?
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 3:48 pm

nearly_takuan wrote:I'm a little confused about using the term "fastest" when it looks like you are storing distances but not times.

I'm also not sure why you want LinkedLists. A sorted heap (or sorted list) seems more efficient for this task. (One heap/list per location, and a HashMap to give you those lists, using the Location as the key.)

Been a while since I touched Java, though; is it already easy to keep a LinkedList sorted?

Sorry, Distance should really be Times (I misread the instructions at first.)

I'm using LinkedList mostly out of a lack of knowledge of what else to do. We've been taught a few data structures: Array, ArrayList, LinkedList, Stack, Queue, HashMap. So I'm mostly trying to sort through these to figure out if I can get what I need.

Looks like you can sort using an inherited Collections method by comparing one string with another. However, sorting isn't really the problem. It's trying to keep the "groupings" together.

So if I have an Array List [LocationName1, Time1, LocationName1, Time2, LocationName2, Time3, LocationName2, Time4], I need to keep the appropriate times with the appropriate locations. If I sort the ArrayList/LinkedList at all, those times are no longer "connected" to their location.

One idea I have is to put LocationName and Time into the same LinkedList, then break them apart into two different arrays by data type (String and Double, respectively.) Then, I'll use the HashMap.contains method. If the HashMap already contains the LocationName, I'll add +1 to an Integer. I'll then use that Integer as the index of the Time array, and then maybe add that Time to a different array. Then I can loop through that last array to find the minimum value.

Or is that hopelessly complicated? I can't think of an easy way to do this. The best would be a HashMap, since I can couple LocationName with a Time, but it'll only store the very last value you give it....
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 4:05 pm

That sounds very complicated. You are kind of forcing yourself to maintain multiple lists and arrays parallel to each other, when really you just want to group things based on their location.

You can use any type as a key for a HashMap. You can use any type as a value. So to me it makes sense to use a location as the key, and a list of times as the value. If the list is kept sorted, with the fastest time at the top, then finding the fastest time will be easy, too.
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 4:49 pm

If you're concerned about your later need to iterate over all locations, you can use map.keySet to get a collection of all the locations you stored.

Naturally, use map.containsKey to decide whether you should create a new list to add to the map or retrieve an existing list and add a new time to it.
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 5:41 pm

nearly_takuan wrote:
You can use any type as a key for a HashMap. You can use any type as a value. So to me it makes sense to use a location as the key, and a list of times as the value. If the list is kept sorted, with the fastest time at the top, then finding the fastest time will be easy, too.

That's what I started with originally, but like I said, it was printing out only the latest time is kinda driving me batty.

Going off your latest post, is your idea that I should have a separate map for each location and then a LinkedList for each time?

So.... ask a user for a location. Ask a user for a time. The location triggers a method to see if that location is in the HashMap. It if isn't, add it, then add the time to a new LinkedList. If the location exists, add the time to an existing LinkedList. Then use that LinkedList to iterate for the fastest time. Add the fastest time to the HashMap with the key of the location.

What do you think? Does that sound more plausible/less complicated?
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 6:16 pm

That sounds close, yeah. Though I'm thinking you can just use exactly one HashMap instance through your entire project. One key per location. One list of times per key, stored as the "values" in your HashMap.

When you get a (location, time) pair, check to see if the map contains location as a key. If it doesn't, create a new Linked List and add it to the map under the key location.

Then use map.get(location) to obtain a LinkedList or ArrayList (which may or may not be empty). Insert time in that list.

When you're done getting entries, find out how many locations you have by using map.keySet(). For each location in the set, print that location, then get() the corresponding list of times, find the smallest element in the list, and print that.

If you're allowed to do a bit of exploration into packages you haven't necessarily been taught, check out java.util.Collections. There's a neat-o sort() method in there that will work on lists if they contain only doubles!
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 6:39 pm

nearly_takuan wrote:That sounds close, yeah. Though I'm thinking you can just use exactly one HashMap instance through your entire project. One key per location. One list of times per key, stored as the "values" in your HashMap.

When you get a (location, time) pair, check to see if the map contains location as a key. If it doesn't, create a new Linked List and add it to the map under the key location. Then use map.get(location) to obtain a LinkedList or ArrayList (which may or may not be empty). Insert time in that list.

Poking at that, I get an error, I think because my ArrayList is a double and my value is a String. Here's my code:

Code:
HashMap map = new HashMap();
        LinkedList<Double> times = new LinkedList<Double>();

        if (map.containsKey(location)){
            times.add(time);
            map.get(location).add(times);
          }

Do you see anything off that I'm doing?

(Also thank you thank you thank you for helping with this, I've been crying in the bathroom every hour for the last day trying to figure this out.)
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 6:49 pm

No problem; I hope I'm helping some.

I think you want to explicitly use a HashMap<String, LinkedList<Double>>. That'll make it a little easier for you and your instructor to see what's going on.

Assuming map.get(location) gives you a LinkedList<Double>, you should just add the time (in the form of a Double) directly to that list. What your code does right now is add the time to a different list, then attempt to add that list to another list. (And because a LinkedList<Double> is not a Double, it fails to compile.)

Keep in mind that you also want to make sure you're creating a new LinkedList<Double> when the map does not contain the location.
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 7:00 pm

Hm I tried adding the time directly

Code:
if (map.containsKey(location)){
          h.get(location).add(time)
}

and I still get the error. "Cannot resolve method add(double.)" This is even after I specify the HashMap as a String and Double.

I think I may need to abandon both displaying all of my times AND finding the fastest time. What I'm trying now is to just calculate the smallest value, and simply add that to the HashMap, instead of trying to keep track of all the times AND calculate the value, if that makes sense. But none of the methods I'm trying to get the small value out are working...

I was able to figured out sort
Code:
times.sort(null)
but how do I pull the smallest value out of that?
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 7:16 pm

If you use a HashMap<String, Double> then you can only store one Double per String. But if you use a HashMap<String, LinkedList<Double>>, then you can store an entire list of Double values per String. Does that help?
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Wed Feb 18, 2015 7:37 pm

nearly_takuan wrote:If you use a HashMap<String, Double> then you can only store one Double per String. But if you use a HashMap<String, LinkedList<Double>>, then you can store an entire list of Double values per String. Does that help?

Sort of, though I admit I've kind of given up on that part. I've gotten the LinkedList to sort, but I don't know how to get ONLY the smallest value out of the sort. I'm also somehow ending up with ALL of the times I've entered, and I don't get how.... Any ideas? Also is it too early in the day to shoot myself?

Code:
if (map.containsKey(location)){
            for (int i = 0; i < newTimes.size(); i++){
                times.add(newTimes.get(i));
            }
            times.add(time);
            getFastTime(times);
            h.put(location, times);
        }else{
            newTimes.clear();
            newTimes.add(time);
            getFastTime(newTimes);
            map.put(location, newTimes);
        }

public static void getFastTime(LinkedList times){
      times.sort(null);

    }
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Wed Feb 18, 2015 8:12 pm

I'm guessing newTimes is a single LinkedList, so you're putting the same list in every map key and adding every time to the same list no matter what location you've got.

You're also updating the map with that list every time, even when you already have a list registered for that key.

Think of the map as a cabinet with labeled drawers. The keys are the labels. The values are the drawers.

On each label, you write the name of a different location. Now you can easily tell which drawer contains the information you need for any of those locations, and you can tell whether or not you already have a drawer for a given location.

But the computer is a little bit more magic than a drawer-based filling system. You've created one LinkedList, outside the loop, in which you are storing every running time you receive, and then you're putting that list in every drawer. (Imagine putting a binder in one drawer, then finding it in a different drawer. You put a sheet of paper in the binder, and that sheet of paper is now in all the other drawers too.)

The new keyword is used to make new instances of an object. You will want an instance of LinkedList<Double> in every mapped value.

Once you have an instance, you can add Double values to it without needing to make further changes to your map.

Code:
HashMap<String, LinkedList<Double>> map = new HashMap<String, LinkedList<Double>>;
while ( /*get input from user, or whatever */ ) {
  // Get location and time
  if (!map.containsKey(location)) {
    LinkedList<Double> times = new LinkedList<Double>
    map.put(location, times);
  }
  // Now our map is guaranteed to have a unique list corresponding to location, even if it is empty. So we can add things to whatever is in there.
  map.get(location).add(time);
}

Result: map is a mapping of locations onto lists of times. These times are not sorted yet, but you already know how to do that part. And once a list is sorted from smallest to greatest, you know where its smallest element is!
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Izmuth Thu Feb 19, 2015 9:00 am

Did you already learn classes/Objects?

I think it could be more intuitive for you if you create a class Location, like so:

Code:
private class Location
{
      LinkedList<Double> times=new LinkedList<Double>();
      String name;

      Location(String nameOfLocation)
      {
            name=nameOfLocation%3B
      }
      void addTimeRan(double time)
      {
               times.add(time);
      }
      double getFastestTime()
      {
              times.sort(null);
              return times.get(put relevant index here since you know where to find the smallest time after you sort the values).doubleValue();
      }
}

and then you can use Nearly's example:

Code:
HashMap<String, Location> map = new HashMap<String, Location>;
while ( /*get input from user, or whatever */ ) {
 // Get location and time
 if (!map.containsKey(location)) {
   map.put(location, new Location(location));
 }
 // Now our map is guaranteed to have a unique list corresponding to location, even if it is empty. So we can add things to whatever is in there.
 map.get(location).addTimeRan(time);
}

EDIT: By the way, at my end times.sort(null) doesn't work. I have to use Collections.sort(times).
Izmuth
Izmuth

Posts : 145
Reputation : 81
Join date : 2014-10-02

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Guest Thu Feb 19, 2015 10:39 am

Piggy-backing off of Izmuth's suggestion, with the data structures you've described, I'd be inclined to define a "Run" object, with variables location and time.

With a LinkedList of Run objects, you can iterate through it and print out "location" and "time" for each. To add a new run, you would iterate through your list to see if you had a Run object for your location. If you did, you could compare the times and set a new one if needed. Otherwise, you could add a new Run at the end of the list.

Guest
Guest


Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Izmuth Thu Feb 19, 2015 11:23 am

Piggybacking onto EJ's suggestion in turn, I've got another solution, if you already have been exposed to interfaces.

Spoilered to prevent confusion in case you already have what you're looking for (can someone take a look to see if I explain it clearly?):
Spoiler:
Izmuth
Izmuth

Posts : 145
Reputation : 81
Join date : 2014-10-02

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by reboundstudent Thu Feb 19, 2015 12:15 pm

I have not yet been exposed to Interfaces. We did just learn about Objects, but I had no idea if I was "allowed" to use them for this assignment (professor never responded to my email.) to be safe, I thus stayed away from Classes, even though damn would that have been so much easier.

This is what I ended up with:

Code:
package Marty.company;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        HashMap<String, List<Double>> h = new HashMap<String, List<Double>>();

        System.out.println("Add a new entry?");
        String userInput = s.next();

        if (userInput.equalsIgnoreCase("Y")) {
            addInformation(h);
        } else {
            printInformation(h);
        }
    }

    public static void addInformation(HashMap<String, List<Double>> h) {
        Scanner s = new Scanner(System.in);

        System.out.println("What lake did you run around?");
        String lake = s.next();

        System.out.println("How fast did you run?");
        double time = s.nextDouble();

        List<Double> timesInMap = h.get(lake);
        if (timesInMap != null) {
            timesInMap.add(time);
            timesInMap.sort(null);
        } else {
            timesInMap = new ArrayList<Double>();
            timesInMap.add(time);
            h.put(lake, timesInMap);
        }

        System.out.println("Add a new entry?");
        String userInput = s.next();
        if (userInput.equalsIgnoreCase("Y")) {
            addInformation(h);
        } else {
            printInformation(h);
        }
    }

    public static void printInformation(HashMap<String, List<Double>> map) {
        Set<String> keySet = map.keySet();
        for (String lakeName : keySet) {
            //Use the key to get each value. Repeat for each key.
            System.out.println("Lake: " + lakeName + " Run Times: " +
                    map.get(lakeName));
        }
    }
}

It.... mostly works. It links the correct time to the correct location, and it sorts them so the fastest times are first in the list. My professor wanted it so ONLY the fastest time printed, but I just could not figure out how to do that. I tried using the following:

Code:
var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;

for (int i=0; i<myArray.length; i++){
  if (myArray[i] < min){
      min = myArray[i];
      minIndex = i;
  }
}

but it'd give me the smallest test for ALL of the locations not each specific location. So I just freaking gave up.

Thank you so much for all the help, guys. I feel very ashamed that I have to ask these really basic questions, but there it is. How did you guys get good at programming? Any tips or study suggestions?
reboundstudent
reboundstudent

Posts : 460
Reputation : 261
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Thu Feb 19, 2015 12:43 pm

To this day, whenever I start getting confused about what's happening in some code I'm reading (mine or anyone else's), I go through each line, carefully, and try to draw out what is happening (using some made-up example input). Usually this means drawing out lots of boxes to show the structures in memory. Sometimes it also helps to vocalize everything I'm thinking, because it slows me down just enough to make sure I spend at least a few seconds seriously considering every thought I have. (Like when I say something stupid and don't realize it until immediately after I say it, but if I hadn't said it I wouldn't have lingered on the thought long enough to realize it was stupid.)

At first, it used to take me a day or so to get enough distance to do that carefully enough, without leaping to conclusions or trying to take heuristic shortcuts, but as with most things one gets better with practice.
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Izmuth Thu Feb 19, 2015 12:53 pm

Personally I would just assume classes are always allowed to be used. They're so vital for readable code and make your life so much easier it doesn't make sense not to allow them. But yeah, I'm not your professor, and it sucks he didn't take five minutes to respond to your query :/

You were thinking too complicated by the way, as soon as you've got an ordered list (assuming its ordered in ascending order), you already know where the smallest value is: it's the first value Razz

You should've replaced
System.out.println("Lake: " + lakeName + " Run Times: " + map.get(lakeName));

with

System.out.println("Lake: " + lakeName + " Run Times: " + map.get(lakeName).get(0));

or

System.out.println("Lake: " + lakeName + " Run Times: " + map.get(lakeName).getFirst());

How I got better at programming? Failing a lot, basically.
I just tried out a lot of things until I finally got something working, then remembered how to do it.
But seeing as that's not really helpful in this moment: maybe it might help to first draw out a step plan how yóu would solve the problem, without a program?

Don't even bother to write it in pseudocode:
"First I'd make a list of all locations with their corresponding time"
"Then I would order them in order of increasing time"

etc. etc. Then you only have to figure out how to translate these steps into code.

And please, we've all been beginners. We're happy to help. Please don't feel ashamed for asking us anything, or I'd feel compelled to start listing all the incredibly obvious mistakes I've made when I started programming, and the obvious mistakes I'm making even now Razz
Izmuth
Izmuth

Posts : 145
Reputation : 81
Join date : 2014-10-02

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Fri Feb 20, 2015 4:03 am

#!begin tangential_rant

Incidentally, this is one of the reasons I often advocate strongly for Go and have lobbied my professors to start teaching with it. (They start with C, which is almost as good, for similar reasons.) Java will let you do things like System.out.println("Lake: " + lakeName + " Run Times: " + map.get(lakeName)); and not ask you to clarify what you mean. Worse, the LinkedList<T> class actually has a custom implementation of toString(), so it doesn't even look "wrong" when you concatenate it to a String (implicitly calling the magic method toString()). Go does not allow implicit conversions at all, and has a standardized way of casting between types. It simply won't let you make the mistake of trying to "add" a complex structure (a List) to a String without casting it, and if you don't cast it then the resulting compile error will remind you that map.get(lakeName) is a LinkedList, whereupon you have an opportunity to realize that you didn't actually want to print the whole list in the first place. Then if you do cast it to a string, the output is formatted in brackets/braces appropriate for the underlying type, which gives you another clue that you may be using the wrong variable. (You also wouldn't need to bother with these weird Collection things anyway, because a map[string]([]float64) would take care of everything and be as straightforwardly accessible as most primitive types!)

See for yourselves if you agree! Razz

Code:

// Java
package nearly.takuan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashMap<String, List<Double>> lakeRecords = new HashMap<String, List<Double>>();

        do {
            System.out.println("Add a new entry?");
            String answer = scanner.next();

            bool bNewEntry = answer.equalsIgnoreCase("Y");
            if (bNewEntry) {
                System.out.println("What lake did you run around?");
                String lake = scanner.next();

                System.out.println("How many minutes did it take?");
                double time = scanner.nextDouble();

                addTime(lakeRecords, lake, time);
            } else {
                printBestTimes(lakeRecords);
            }
        } while (bNewEntry)
    }

    private static void addTime(Map<String, List<Double>> records, String lake, double time) {
        if (!records.containsKey(lake)) {
            records.put(lake, new ArrayList<Double>());
        }
        // Implicit conversion of primitive type double to wrapper class Double
        records.get(lake).add(time);
    }

    private static void printBestTimes(Map<String, List<Double>> records) {
        Set<String> keySet = records.keySet();
        for (String lake : keySet) {
            // Use the key to get each value. Repeat for each key.
            List<Double> times = records.get(lake);
            // Since the Double class implements the Comparable interface, a "null" Comparator causes the sort() method to use the "natural ordering" of Doubles: least to greatest.
            times.sort(null);
            System.out.println("Lake: " + lake + "\nRun Times: " + times.get(0) + "\n");
        }
    }
}

Code:

// Go
package main
import (
  "bufio"
  "fmt"
  "os"
  "sort"
  "strconv"
  "strings"
)

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  records := make(map[string][]float64)
  
  for {
    fmt.Println("Add a new entry?")
    scanner.Scan()
    answer := scanner.Text()
    
    if strings.ToUpper(answer) != "Y" {
      printBestTimes(records)
      return
    }

    fmt.Println("What lake did you run around?")
    scanner.Scan()
    lake := scanner.Text()

    fmt.Println("How many minutes did it take?")
    scanner.Scan()
    time := strconv.ParseFloat(scanner.Text(), 64)

    addTime(&records, lake, time)
  }
}

func addTime(records *map[string][]float64, lake string, time float64) {
  if _, exists := records[lake]; !exists {
    (*records)[lake] = make([]float64)
  }
  (*records)[lake] = append((*records)[lake], time)
}

func printTimes(records map[string][]float64) {
  for lake, times := range records {
    sort.Float64s(times)
    fmt.Printf("Lake: %s\nRun Times:%f\n\n", lake, times[0])
  }
}

Note: A "double" in Java/C++ is a floating-point value with double the number of bits (i.e. precision) of a 32-bit "float". The designers of the Go language decided to just call the datatypes float32 and float64, so that if some day in the far future people start commonly using float128s they don't have to support a "quadruple" primitive type.

(Note 2: I haven't run either of the above code snippets through a compiler, so I'm not 100% certain the logic is perfect. In the words of Knuth, I've only proved it correct!)
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Guest Fri Feb 20, 2015 10:12 am

I am so fascinated by the idea of Go as a language. I love their take on interfaces and error handling.

I haven't studied it thoroughly, but I'm on the lookout for somewhere I can apply it in my work, and may just pick up a personal project to play with it.

Is Go also the one that lets you return multiple things? I haven't looked at the pages in a while, so I don't remember it all.

To answer RBS's question, I mostly got good at programming by doing it. Not for class assignments, though -- I started at around 16, when I was playing a text-based online game (MOOs!) and someone broke all the code and left. I was the only one who had the time and a TINY amount of know-how, so I had to just dive in and hack at it until it worked.

It took probably 20+ hours in the first weekend, and then hours a day for a few weeks later, but I emerged knowing the basics. From there, I just kept doing new things that interested me.

Guest
Guest


Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Izmuth Fri Feb 20, 2015 1:48 pm

reboundstudent wrote:
My professor wanted it so ONLY the fastest time printed, but I just could not figure out how to do that. I tried using the following:

Code:
var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;

for (int i=0; i<myArray.length; i++){
   if (myArray[i] < min){
      min = myArray[i];
      minIndex = i;
   }
}

but it'd give me the smallest test for ALL of the locations not each specific location. So I just freaking gave up.

By the way, I *think* you might have made a mistake with the scope of variables, and that's why your snippet to get the smallest value didn't work.

This would work the way you intend it to:
Code:


    public static void printInformation(HashMap<String, List<Double>> map) {
        Set<String> keySet = map.keySet();
        for (String lakeName : keySet) {
              //start looking for the smallest set:
              List<Double> timesRanAtLocation=map.get(lakeName);
              //smallest is set to the maximum value a double can be every iteration
              double smallest=Double.MAX_VALUE;
              for(double currentNumber:timesRanAtLocation){
                    if (smallest>currentNumber)
                    {
                          smallest=currentNumber;
                    }
              }
              System.out.println("Lake: " + lakeName + " Run Times: " + smallest);
              //java forgets variable smallest exists
        }
    }
}


this wouldn't:

Code:


    public static void printInformation(HashMap<String, List<Double>> map) {
        Set<String> keySet = map.keySet();
        //Scope of variable smallest is now wrong!
        double smallest=Double.MAX_VALUE;
        for (String lakeName : keySet) {
              //start looking for the smallest set:
              List<Double> timesRanAtLocation=map.get(lakeName);
              //java still remembers the smallest value of the previous iteration, because we didn't set it to the maximum value this iteration!
              for(double currentNumber:timesRanAtLocation){
                    if (smallest>currentNumber)
                    {
                          smallest=currentNumber;
                    }
              }
              System.out.println("Lake: " + lakeName + " Run Times: " + smallest);
              //variable smallest still not forgotten, smallest time of previous iteration goes over to next iteration
        }
        //java only forgets variable smallest exists at this point
    }
}


What also helps is debugging your code. You can (depending on your program you use to code it with) tell it you want it to go through your program line for line, and see where it does not behave as expected.

Example for Eclipse: http://www.vogella.com/tutorials/EclipseDebugging/article.html

@Discussion about Go/Java (spoilered for being offtopic)
Spoiler:
Izmuth
Izmuth

Posts : 145
Reputation : 81
Join date : 2014-10-02

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by LadyLuck Tue Feb 24, 2015 1:10 am

Experienced-ish Java programmer here.

On nearly's suggestion of this Go language - your argument appears to be that stronger-typing = easier to learn. Except that lots of people cite Python as an "easy to learn" language which kind of flies in the face of that. This is also besides the fact that Java/C/C++ are pretty much the most strongly-typed languages that are widely used (that I can think of, anyway). So even if it would be preferable to learn via a language with strong typing, you really can't get more strongly-typed then Java unless you're willing to dump time into a language that has little marketability.

On learning/improving programming in general - agreed with everyone that said you just need to program a lot. And yeah, just doing your class projects is not going to be enough to "get good" (Read: get hired). Typically classes will assign one program that you work on in between other classwork over the course of 1 or 2 weeks. It probably won't take more then a couple hundred lines of code, at most. This is quite small volume-wise compared to a professional software engineer, who is expected churn out that much in a single day. Furthermore, a programming assignment is designed to not require any concepts or code libraries/frameworks beyond what was specifically taught in class. In contrast, I am currently being expected at my job to learn a 4-part development stack based on a language I've barely ever used (javascript). I also have had to independently read up on various pieces of Android functionality as well - and I'm not even a full-time developer! Doing personal projects gives you the much more relevant skill of being able to learn on your own, without a teacher specifically guiding you step-by-step, without already knowing in advance that there's even a solution at all. And that will be far more useful and impressive to prospective employers.

LadyLuck

Posts : 48
Reputation : 45
Join date : 2014-11-18

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by nearly_takuan Tue Feb 24, 2015 1:30 am

Eh, my argument is more that when there are things a language lets you get away with, it's possible to do "well enough" without really understanding why, which gives novices the impression that it's all magic / that they can take advantage of and rely on whatever-it-is and move on.

Java is strongly-typed except in the very special case of Strings. It also wisely prohibits operator overloading...except in the very special case of Strings. Raw data is primitive, and object instances must be explicitly defined using new...unless you're working with String literals.

And it's nice sometimes, having your language encrusted in carmelized syntax. It's just that I always find the hardest thing about learning to write good code was (and the hardest thing about teaching it is) explaining where things went wrong.

Go is beautiful to me because a logical error expressed in the language is usually also a syntax error. (The correlation is of course still not perfect, but my experience has been that it still seems almost on par with Yacc!) There are other languages that work similarly, too. I just happen to believe that Java is not a great first language to learn. Shrug.

Still, Java isn't the worst, either. The point about it being more generally marketable is true. And Turing-complete languages are all more or less interchangeable anyway. Practice will always help. So will going through your own code slowly, objectively, carefully. So will running debugger tools and observing how memory is accessed and used.
nearly_takuan
nearly_takuan

Posts : 1071
Reputation : 461
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by kath Sat Feb 28, 2015 12:43 pm

Re: generally getting better at programming, I'm responding as a different case. I don't have formal computer science training, and the extent to which I've been employed as a programmer was as a web developer, not writing software. And whether or not I'm good at it is another question all together, but I can make existing systems do what I want them to do and add functionality to things like Wordpress, and I also do a fair amount of electronics and physical computing projects (and not ones that are lifted directly from Make or Instructables, as much fun as replicating a cool project is).

And I think practice is really important, but I think more important than practice with a particular language or whatever is practice breaking down your project and figuring out what you actually need to do, and then practice reading and understanding instructions that will help you get there. That's what makes it possible to orient yourself in an unfamiliar language, pull in solutions you weren't expecting to use, etc. I was teaching an arduino workshop at work, and that workshop wasn't actually about learning arduino or processing ... it was about learning how to plug away at something and keep trying stuff as you get incrementally closer to your goal (which has to be really cool).
kath
kath

Posts : 352
Reputation : 159
Join date : 2014-10-01

Back to top Go down

Forum Help: Calling Other Programmers!  Empty Re: Forum Help: Calling Other Programmers!

Post by Sponsored content


Sponsored content


Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum