Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Roberto Monteiro Dias

Dificuldade em ler dados .txt ao executar o algoritmo Stable Marriage em Java

Recommended Posts

Eu sou novo em Java e estou tentando executar o algoritmo Stable Marrage de GaleShapley, mas ao executá-lo, aparece o  seguinte erro:

 

Error: Index 3 out of bounds for length 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    at br.com.entrada.GaleShapley.calcMatches(GaleShapley.java:48)
    at br.com.entrada.GaleShapley.<init>(GaleShapley.java:33)
    at br.com.entrada.GaleShapley1.main(GaleShapley1.java:164)
Gale Shapley Marriage Algorithm

Sized : 3

 

Segue o código abaixo:

 

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
    /** Constructor **/
    public GaleShapley (){

    }
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
    System.out.println("Sized : "+  mp.length);
    N = mp.length;
    engagedCount = 0;
    men = m;
    women = w;
    menPref = mp;
    womenPref = wp;
    menEngaged = new boolean[N];
    womenPartner =  new String[N];
    calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
    while (engagedCount < N)
    {
        int free;
        for (free = 0; free < N; free++)
            if (!menEngaged[free])
                break;

        for (int i = 0; i < N && !menEngaged[free]; i++)
        {
            int index = womenIndexOf(menPref[free]);
            if (index  < womenPartner.length && womenPartner[index] != null  )
            {
                womenPartner[index] = men[free];
                menEngaged[free] = true;
                engagedCount++;
            }
            else
            {
                String currentPartner = womenPartner[index];
                if (morePreference(currentPartner, men[free], index))
                {
                    womenPartner[index] = men[free];
                    menEngaged[free] = true;
                    menEngaged[menIndexOf(currentPartner)] = false;

                }
            }
        }            
    }
    printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
    for (int i = 0; i < N; i++)
    {
        if (womenPref[index].equals(newPartner))
            return true;
        if (womenPref[index].equals(curPartner))
            return false;
    }
    return false;
}
/** get men index **/
private int menIndexOf(String str)
{
    for (int i = 0; i < N; i++)
        if (men.equals(str))
            return i;
    return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
    for (int i = 0; i < N; i++)
        if (women.contains(str))
            return i;
    return -1;
}
/** print couples **/
public void printCouples()
{
    System.out.println("Couples are : ");
    for (int i = 0; i < N; i++)
    {
        System.out.println(womenPartner +" "+ women);
    }
}
/** main function **/
public static void main(String[] args) throws IOException{
    System.out.println("Gale Shapley Marriage Algorithm\n");
    /** list of men **/
    String[] m = {"1", "2", "3"};
    /** list of women **/
    String[] w = {"1", "2", "3"};

    /** men preference **/


    String[][] mp = null ;
    /** women preference **/                      
    String[][] wp= null ;


    try{
      FileInputStream fstream = new FileInputStream("src/input.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      int line=0;
      int k=0;
      int n=0;
      int i=0;
      while ((strLine = br.readLine()) != null)  {
         
         if(line==0){
            
            n =Integer.valueOf(strLine.trim());
            mp=new String[n][n];
            wp=new String[n][n];
            line++;
         }
         else{

             String[] preferences=strLine.split(" ");

             if(i<n){
                 mp=preferences;
             }
             else{
                 if(i-n < w.length) {
                     wp[i-n]=preferences;

                 }
             }
             i++;
         }
      }
      in.close();

      GaleShapley gs = new GaleShapley(m, w, mp, wp);                        

        }catch (Exception e){//Catch exception if any
            e.printStackTrace();  
            System.err.println("Error: " + e.getMessage());
        }
   }


}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Estou escrevendo um Sistema Java Web e quando clico no Botão Salvar, o Java acusa esse erro:

      ERROR: Cannot invoke "Object.toString()" because the return value of "java.util.Map.get(Object)" is null
       
      Já tentei de várias formas resolver esse problema, mas não estou conseguindo.

      Por favor, alguém pode me ajudar identificar a origem e resolver o problema acima ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.

      Estou enfrentando um problema que não consigo entender.

      Após Instalar o MySql versão 8.0.36, funciona corretamente realizando as conexões.

      O problema é:
      ---[ após reiniciar o micro, o MySql não faz as conexões.
      --[ tenta localizar este arquivo, mas não acha: my.ini
       
      Onde localizo ou configuro este arquivo na Pasta MySql ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, preciso de ajuda em Relação a Instalar o Jasper Reports no Eclipse, pois a opção de Eclipse Marketplace, não encontra para instalar.
       
      Já tentei de todas as formas mas não consegui, alguém conhece alguma rotina explicando este procedimento ?
       
      Grato,
       
      Cesar
    • Por violin101
      Caros amantes da informática.
       
      Saudações.
       
      Estou usando o Eclipse Mars versão 4.5.0  e o 4.5.2, acredito que deva ter versões mais novas. 
      Sou novato em JAVA e estou encontrando alguns problema em Instalação de alguns plugins, como por exemplo:
       
      1) quando tento instalar o JBoss Tools através do Eclipse Marteplace, o Eclipse não o encontra na lista de plugins.
      2) se tento instalar através do Install New Software, abaixa alguns arquivos, mas também não instala o JBoss.
      3) se abro o site e arrasto o download para a área de trabalho do Eclipse, também não instala o JBoss.
       
      Caros amigos, existe outra alguma forma de instalar o JBoss Tools no Eclipse e como seria ?
       
      Grato,
       
      Cesar
       
       
    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.