how to create vector vectors?

0

Can anyone tell me how to create a vector vector in java? ie How to make a vector store other vectors with int values

Tie this populates a vector with values from 1 to 4 q are directions N = North, S = South, East L =, O = West.

for (int i =0; i < aux; i ++) {

        v[i] = (int) (Math.random() *4);

        if(v[i] == 0){
             N++;
        System.out.println("N");}
        if(v[i] == 1){
            S++;
        System.out.println("S");}
        if(v[i] == 2){
            L++;
        System.out.println("L");}
        if(v[i] == 3){
            O++;
        System.out.println("O");} 
    }

My goal is to store results in 4 other vectors

    
asked by anonymous 29.11.2018 / 17:24

2 answers

0

You can create a list of vectors using the List interface ( read more about the interface and its methods by clicking here ), by implementing the ArrayList class. Following your example, it would look something like this:

List<int[]> listaDeVetores = new ArrayList<int[]>();
for (int i =0; i < aux; i ++) {
    v[i] = (int) (Math.random() *4);

    if(v[i] == 0){
        N++;
        System.out.println("N");}
    if(v[i] == 1){
        S++;
        System.out.println("S");}
    if(v[i] == 2){
        L++;
        System.out.println("L");}
    if(v[i] == 3){
        O++;
        System.out.println("O");}
    //adiciona o vetor da vez na lista.
    listaDeVetores.add(v);
}
But analyzing the problem that you proposed, there are always 4 "directions" that exist, so I would create a class with the attributes N, S, L, and O, and it would list only this class and not a list of vectors, thus making it easier to maintain and manipulate attributes.

    
29.11.2018 / 18:14
0

You can also use HashMap . See code below:

import java.util.HashMap;
import java.util.Map;

public class SingleObject {

    private static SingleObject instance;

    private static Map<String,Integer> pontos = new HashMap<String,Integer>();

    private SingleObject() {
        pontos.put( "N", 0);
        pontos.put( "S", 0);
        pontos.put( "L", 0);
        pontos.put( "O", 0);
    }

    public static SingleObject getInstance(){
        if(instance == null)
            instance = new SingleObject();
        return instance;
    }

    public void increment(String opcao) {
        Integer opc = pontos.get(opcao);
        pontos.replace(opcao, opc + 1);
    }

    public void exibir() {
        System.out.println(pontos);
    }

    public static void main(String[] args) {
        SingleObject o = SingleObject.getInstance();
        o.increment("L");
        o.increment("N");
        o.increment("N");
        o.increment("N");
        o.increment("O");
        o.exibir();

        o.increment("L");
        o.increment("O");
        o.increment("N");
        o.increment("S");
        o.increment("S");
        o.increment("O");
        o.exibir();
    }
}
    
29.11.2018 / 18:16