DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

2 1

HackerRank #33 | Arraylist | 🇧🇷

Neste exercício devemos receber vários inputs diferentes.
O exercĂ­cio Ă© bem complexo de ser compreendido (precisei de ajuda pra entender o enunciado) e vou tentar explicar da melhor forma possĂ­vel. Para isso, vou dividir o exercĂ­cio em duas partes:

=========

Parte I

  • Recebemos um int n. Este int delimita a quantidade de Arrays que teremos na lista.
  • Recebemos um int d. Este int delimita a quantidade de elementos dentro do array.

Exemplo (n = 2 | d = 3, 4):

2
3 11 22 33
4 54 12 3 12
Enter fullscreen mode Exit fullscreen mode

Logo, todos os primeiros nĂşmeros estĂŁo, na verdade, ordenando a quantidade de listas ou a quantidade de elementos da lista.

Para resolver essa primeira parte do problema segui o seguinte passo a passo:

  • Fiz o Scanner
  • Peguei o int n a partir desse Scanner
  • Criei um ArrayList[] nArray = new ArrayList[n] (n significa que o nĂşmero de arrays obedecerá o input n
  • Fiz um for que pega, atravĂ©s do scanner.nextInt() cada novo Array atravĂ©s de d.
  • Dentro do for, fiz outro for declarando um int j que fará a substituição de cada posição [i] dos arrays.

Ficou mais ou menos assim:

        Scanner scanner = new Scanner(new File("input.txt"));
        int n = scanner.nextInt();
        int d;

        ArrayList[] nArray = new ArrayList[n]; // n Ă© a quantidade de arrays

            for (int i = 0; i < n; i++) {
                d = scanner.nextInt();
                nArray[i] = new ArrayList();
                for (int j = 0; j < d; j++){
                    nArray[i].add(scanner.nextInt());
            }
        }
Enter fullscreen mode Exit fullscreen mode

Perceba que o primeiro for percorre o tamanho de n enquanto que o segundo for percorre o tamanho de d. Isso significa que só fazemos o segundo array depois que passamos por todos os elementos dele e assim até que o número de arrays seja menor < do que n

=========

Parte II

Agora vem a segunda parte do problema. Aqui recebemos outro int chamado q e Ă© ele que delimita a quantidade de linhas (chamadas) que vamos ter.
Aqui, escolhemos dois números, x e y. x especifica o número da linha e y especifica o número da coluna. Isso quer dizer que vamos "pegar" um elemento de cada array que declaramos anteriormente através de x e y.
A ilustração do problema pode ser mais clara:

Alt Text

Aqui a ilustração que fiz para entender melhor os ints n, d e q.

Alt Text

Para resolver a segunda parte, fiz o seguinte passo a passo:

  • Declarei o int q = scanner.nextInt()
  • Declarei tambĂ©m x e y, sem inicializá-los. > É importante declará-los fora do for que vamos fazer, porque usaremos mesmo quando a iteração acabar.
  • O for consiste em iterar a letra h atĂ© que o tamanho seja menor < do que q e escanear x e y. Assim:
            int q = scanner.nextInt();
            int x;
            int y;

            for (int h = 0; h < q; h++){
                x = scanner.nextInt();
                y = scanner.nextInt();
Enter fullscreen mode Exit fullscreen mode

Por fim, para que o console devolva a mensagem ERROR! caso x e y não convirjam, é necessário fazer um try / catch. Nesse caso, como os Arrays começam na posição 0 (e não levamos isso em consideração para declarar as posições em x e y), precisamos especificar no try que a posição que queremos é, na verdade, x - 1 e y - 1.
No catch declaramos que a Exception e gera um System.out.println("ERROR!");.

O cĂłdigo final fica assim:

public class Solution {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int d;

        ArrayList[] nArray = new ArrayList[n];

            for (int i = 0; i < n; i++) {
                d = scanner.nextInt();
                nArray[i] = new ArrayList();
                for (int j = 0; j < d; j++){
                    nArray[i].add(scanner.nextInt());
            }
        }
            int q = scanner.nextInt();
            int x;
            int y;

            for (int h = 0; h < q; h++){
                x = scanner.nextInt();
                y = scanner.nextInt();
                try{
                    System.out.println(nArray[x-1].get(y-1));
                } catch(Exception e){
                    System.out.println("ERROR!");
                }
            }

        scanner.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

=========

ReferĂŞncias

ArrayList : Oracle

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

đź‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay