Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Create a set from a double value from an split string in an array

I have some issues with a current exercise where I have to look up at an array of 1000 strings that are split by "," into siteId, siteName, year,month, day, hour and temperature. The information I need is an integer, which is the day when it was recorded, and a double which is the temperature.

For example,

I get a record from a weather station with the values 3031,LOCH GLACARNOCH SAWS (3031),2015,01,01,18,7.50

So far I have tried to make an arrayList and so with the dates, as there can be no duplicates, but In cannot find the solution to the question: How many days did the temperature fall to 0.0 or below anywhere in the UK?

The year variable is not so important as the records are only from 2015.

String[] weatherData = WeatherData.getData();

    double zeroTemp = 0.0;
    int counter = 0;
    // get the data
            
    
    for (int i = 1; i <= weatherData.length-1; i++) {
        
        String line = weatherData[i];
        String[] data = line.split(",");
        int date = Integer.parseInt(data[6]);
        int month = Integer.parseInt(data[5]);
        int year = Integer.parseInt(data[4]);
        double temp = Double.parseDouble(data[9]);
            
        LocalDate when = LocalDate.of(year, month, date);
        
        for(int j = 1; j<= data.length; j++) {
        HashSet<LocalDate> duplicateDates = new HashSet<>(Arrays.asList(when));
        System.out.println(when);
          duplicateDates.add(when);
        
        System.out.println(duplicateDates.size());
        }
        if(zeroTemp >= temp) { 
            counter++;      
            }
        }
        System.out.println("The temperature fell to 0.0 degrees or below in " + counter  + " days.");
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The information I need is an integer, which is the day when it was recorded

Not really.

Either the input may contain multiple entries for a single date, in which case you need to know the entire date (even if year is irrelevant, there's month + day; you can't just look at that 'day' value, or you'd consider 1st of March and 1st of April as the same day which is clearly incorrect.

Or, there are no duplicates: For any given exact day, there can only ever be a single record. This sounds wrong (given the "or below anywhere in the UK?" part), but if so, you don't need to look at day or month whatsoever; just count the # of entries with a temperature recording below 0.

You could hack it and turn the month and day fields into a single unique integer (multiply month by 32, then add days: That guarantees you a unique 'month+day' ID value, because no month has 32 days, overlap is not possible). Or write it properly and turn that year+month+day field into a LocalDate instance: LocalDate when = LocalDate.of(2015, 1, 1) would produce a LocalDate instance representing jan 1st 2015.

ArrayList isn't a good tool for uniqueness; you're probably looking for HashMap which maps a given 'key' to a given value, or better yet, a HashSet, which stores values, but which will not store the same value more than once. You can then add any LocalDate for which you have found a record at sub-zero, and if you then find another such record, you'd not change anything - just add the date to the set a second time, as it won't have any effect. Then at the very end just check how large the set is. So:

  1. Create a HashSet of LocalDate.
  2. For each record: Write code that turns the year, month, and day values into a LocalDate, using LocalDate.of(year, month, day).
  3. Check if the temperature value is below 0.0. If so, add the date you made to the set.
  4. When done with the loops, the size of the set represents the # of days that the temperature was below 0 anywhere in the UK.

NB: line.split(",") will take a line of text and return a string array by splitting the input line at each comma. Integer.parseInt("50") returns the number 50.

This should be all the info you need to finish your homework.

over 4 years ago · Santiago Trujillo Relatório

0

You have mentioned that the dates are unique. Based on the condition, you can do it with the following simple steps:

  1. Put the records into a Map<LocalDate, Double> to store date as the key and the temperature as the value.
  2. Iterate the Map values and count the number of times the temperature is found to be less than zero.

Demo:

// Put the records in a Map<LocalDate, Double>      
Map<LocalDate, Double> map = new HashMap<>();
for (int i = 0; i < weatherData.length; i++) {
    String line = weatherData[i];
    String[] data = line.split(",");
    int day = Integer.parseInt(data[6]);
    int month = Integer.parseInt(data[5]);
    int year = Integer.parseInt(data[4]);
    double temp = Double.parseDouble(data[9]);

    LocalDate date = LocalDate.of(year, month, day);

    map.put(date, temp);
}

// If you wish, you can print the map to view the datewise-records of temperature
System.out.println(map);

// Iterate the map values and count the number of times the temp < 0    
int count = 0;
for (Double value : map.values()) {
    if (value < 0) {
        count++;
    }
}

System.out.println("The temperature fell to 0.0 degrees or below in " + count + " days.");
over 4 years ago · Santiago Trujillo Relatório

0

Finally! Thank you so much for your help, guys.

I finally did it.

//How many days of the year did the temperature fall to 0.0 or below
    //anywhere in the UK? Hint : More than 200 but less than 250
    String[] weatherData = WeatherData.getData();
    
    double zeroTemp = 0.0;
    HashSet<LocalDate> set = new HashSet<>();
    // get the data
            
    
    for (int i = 1; i <= weatherData.length-1; i++) {
        
        String line = weatherData[i];
        String[] data = line.split(",");
        int date = Integer.parseInt(data[6]);
        int month = Integer.parseInt(data[5]);
        int year = Integer.parseInt(data[4]);
        double temp = Double.parseDouble(data[9]);
        LocalDate when = LocalDate.of(year, month, date);
        
        if(zeroTemp >= temp) { 
        set.add(when);
            }
        }
    System.out.println("The temperature fell to 0.0 degrees or below in " + set.size()  + " days.");    
}

I just had to put a HashSet outside of the for loop and only enter a new value if the temperature was below or equal to 0.0

I don't know how I wasn't able to see it.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda