mercredi 18 décembre 2019

Random Algorithm in java [closed]

I am doing a project in algorithms which consists in associating a word with a seed and a after to the word a sentence. I should have the same words on different platforms, but this doesn't happen. In fact I get different words from the ones I should get. This is my code:

import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Random;
import java.util.Scanner;
import java.io.*;

public class Esercizio1 {
    public static void main(String[] args) {
         try {
            Dictionary<String, String[]> poesie = new Hashtable<String, String[]>();
            Scanner scanner = new Scanner(new FileReader(args[0]));
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(args[1]));
            Random random = new Random();
            long seed = scanner.nextLong();
            System.out.println("Seed: "+seed);
            scanner.nextLine();
            // lettura delle chiavi
            String[] keysArray = scanner.nextLine().split(" ");
            String[] selectedKeys = scanner.nextLine().split(" ");
            // lettura a vuoto
            scanner.nextLine();
          for(int i=0; i<keysArray.length; i++){
                String[] temp = scanner.nextLine().replaceAll("\\s", "").split(":");
                String key = temp[0];
                String[] frasi = temp[1].substring(1, temp[1].length()-1).split(",");
                poesie.put(key, frasi);
            }
            scanner.close();
            // scrivo output su file
            for(int i=0; i<  selectedKeys.length; i++){
              Casuale rnd = new Random ();
               rnd.setSeed (seed);
                //random.setSeed(seed);
                // estraggo frase tramite chiave
                String[] frasiEstratte = poesie.get(selectedKeys[i]);
                int bound = frasiEstratte.length;
                fileWriter.write(frasiEstratte[rnd.nextInt(bound)]+". ");
            }
            fileWriter.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire