Doubts for create a Totoloto with functions - java

Hi Guys i have a problem in my program of Totoloto. I want create a function for show the six numbers of the key but i can't because in my output show only a one number at end counter position. I make a debug with System.out.println in inside the function numeDeChaves and appears all numbers . If try without functions and its work but i want in function for legible code and learn a little more how to work the functions.
this is wrong output:
Quantas chaves pretende gerar? 6
As chaves geradas são: 1ª chave -> 2ª chave -> 3ª chave -> 4ª chave -> 5ª chave -> 6ª chave -> 36
public static void main(String[] args) {
System.out.println("Totoloto \n");
System.out.println("Quantas chaves pretende gerar?");
int numero = Ler.umInt();
int[] numeroChaves = new int[numero];
int[] chave = new int[8];
System.out.println("");
System.out.println("As chaves geradas são: ");
System.out.println(numeroDeChaves(numeroChaves));
}
public static int numeroDeChaves(int[] numeroChaves){
int contador = 1;
int totalChaves = 0;
for (int i = 0; i < numeroChaves.length; i++) {
System.out.print(contador + "ª chave -> ");
contador++;
for (int j = 0; j < numeroChaves.length; j++) {
numeroChaves[j] = chaveAleatoria(numeroChaves);
totalChaves = numeroChaves[j];
}
System.out.println("");
}
return totalChaves;
}
public static int chaveAleatoria(int chave[]) {
int numeroAleatorio = (int) (Math.random() * 43) + 6;
int ultimoNumero = chave[0] + 1;
int chaveGerada = 0;
int contarChaves = 0;
for (int i = 1; i < chave.length; i++) {
if (chave[i] == chave[i - 1] && ultimoNumero != chave[i - 1]) {
ultimoNumero = chave[i];
chave[i] = numeroAleatorio;
} else {
chave[i] = numeroAleatorio;
chaveGerada = chave[i];
System.out.print("");
}
}
return chaveGerada;
}

Related

How to correctly implement maximum weight independent set of positive tree using BFS

can someone help me implement the maximum weight independent set for a TREE (not a graph)?
The tree is represented by an adjacency matrix, and we have an array for the weights of the vertices.
BFS output: // 0: distances from start vertex
// 1: BFS-order
// 2: parent-IDs
I tried this code, it doesn't work on all test cases and it says most of the time that the weight is too small.
Can someone help me find the errors?
import java.io.*;
import java.util.*;
public class Lab5
{
/**
* Problem: Find a maximum weight independent set using dynammic programming.
*/
private static int[] problem(Tree t, int[] weights)
{
// Implement me!
//base cases
if (t.noOfVertices==0) {
return new int[] {};
}
if (t.noOfVertices==1) {
return new int[] {weights[0]};
}
//we will implement this using bfs, we will use 0 as the root
int[][] bfs = t.bfs(0);
//finding leaves
int leaf[] = new int [t.noOfVertices];
//now we can implement our algorithm
//M is the maximum weight of the tree if it contains i, and M1 is the maximum weight of the tree if it doesn't contain i
int M[]=new int[t.noOfVertices];
int M1[]=new int[t.noOfVertices];
//treating elements that aren't leaves
int nodeDiscovered[] = new int[t.noOfVertices];
for (int i = 0; i<t.noOfVertices; i++) {
if (t.edges[i].length==1) {
leaf[i]=1;
M[i]=weights[i];
nodeDiscovered[i]=1;
M1[i]=0;
}
else {
leaf[i]=0;
nodeDiscovered[i]=0;
}
}
for (int i = 1; i<t.noOfVertices; i++) {
if (leaf[i]==1) {
int node = bfs[2][i];
if (nodeDiscovered[node]!=0) {
continue;
}
while (node>-1) {
int parent = bfs[2][node];
ArrayList<Integer> sibs = new ArrayList<Integer>();
if (parent!=-1) {
for (int j = 0; j<t.edges[parent].length; j++) {
if (t.edges[parent][j]!=bfs[2][parent]) {
sibs.add(t.edges[parent][j]);
}
}
}
else {
sibs.add(node);
}
for (int sib : sibs) {
if (nodeDiscovered[sib]!=0) {
continue;
}
M[sib]=weights[sib];
for (int k : t.edges[sib]) {
if(bfs[0][sib]==bfs[0][k]-1) {
M[sib]=M[sib]+M1[k];
M1[sib]+=(M[k]>M1[k])?M[k]:M1[k];
}
}
nodeDiscovered[sib]=1;
}
node = bfs[2][node];
}
}
}
//putting the answers in an arraylist
ArrayList<Integer> set = new ArrayList<Integer>();
if (M[0]>M1[0]) {
set.add(0);
}
for (int i = 1; i<t.noOfVertices; i++) {
if (!set.contains(bfs[2][i]) && M[i]>=M1[i] ) {
set.add(i);
}
}
System.out.println(set);
//putting the elements of the arraylist into an array of int
int[] set1 = new int[set.size()];
for (int i = 0; i<set.size(); i++) {
set1[i]=set.get(i);
}
return set1;
}
// ---------------------------------------------------------------------
// Do not change any of the code below!
// Do not change any of the code below!
/**
* Determines if a given set of vertices is an independent set for the given tree.
*/
private static boolean isIndSet(Tree t, int[] set)
{
if (set == null) return false;
boolean[] covered = new boolean[t.noOfVertices];
for (int i = 0; i < set.length; i++)
{
int vId = set[i];
int[] neighs = t.edges[vId];
if (covered[vId]) return false;
covered[vId] = true;
for (int j = 0; j < neighs.length; j++)
{
int nId = neighs[j];
covered[nId] = true;
}
}
return true;
}
private static final int LabNo = 5;
private static final String course = "CS 427";
private static final String quarter = "Fall 2021";
private static final Random rng = new Random(190817);
private static boolean testProblem(int[][] testCase)
{
int[] parents = testCase[0];
int[] weights = testCase[1];
Tree t = Tree.fromParents(parents);
int[] solution = maxIsWeight(t, weights);
int isWeight = solution[0];
int isSize = solution[1];
int[] answer = problem(t, weights.clone());
if (!isIndSet(t, answer))
{
System.out.println("Not an independent set.");
return false;
}
int ansWeight = 0;
for (int i = 0; i < answer.length; i++)
{
ansWeight += weights[answer[i]];
}
if (ansWeight < isWeight)
{
System.out.println("Weight too small.");
return false;
}
if (answer.length < isSize)
{
System.out.println("Set too small.");
return false;
}
return true;
}
private static int[] maxIsWeight(Tree t, int[] weigh)
{
int n = t.noOfVertices;
int[][] dfs = t.dfs(0);
int[] post = dfs[2];
int[] w = new int[n];
for (int i = 0; i < n; i++)
{
w[i] = weigh[i] * n + 1;
}
boolean[] isCandidate = new boolean[n];
for (int i = 0; i < n; i++)
{
int vId = post[i];
if (w[vId] <= 0) continue;
isCandidate[vId] = true;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
w[uId] = Math.max(w[uId] - w[vId], 0);
}
}
int isWeight = 0;
int isSize = 0;
for (int i = n - 1; i >= 0; i--)
{
int vId = post[i];
if (!isCandidate[vId]) continue;
isWeight += weigh[vId];
isSize++;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
isCandidate[uId] = false;
}
}
return new int[] { isWeight, isSize };
}
public static void main(String args[])
{
System.out.println(course + " -- " + quarter + " -- Lab " + LabNo);
int noOfTests = 300;
boolean passedAll = true;
System.out.println("-- -- -- -- --");
System.out.println(noOfTests + " random test cases.");
for (int i = 1; i <= noOfTests; i++)
{
boolean passed = false;
boolean exce = false;
try
{
int[][] testCase = createProblem(i);
passed = testProblem(testCase);
}
catch (Exception ex)
{
passed = false;
exce = true;
ex.printStackTrace();
}
if (!passed)
{
System.out.println("Test " + i + " failed!" + (exce ? " (Exception)" : ""));
passedAll = false;
//break;
}
}
if (passedAll)
{
System.out.println("All test passed.");
}
}
private static int[][] createProblem(int testNo)
{
int size = rng.nextInt(Math.min(testNo, 5000)) + 5;
// -- Generate tree. ---
int[] parents = new int[size];
parents[0] = -1;
for (int i = 1; i < parents.length; i++)
{
parents[i] = rng.nextInt(i);
}
// -- Generate weights. ---
int[] weights = new int[size];
for (int i = 0; i < weights.length; i++)
{
weights[i] = rng.nextInt(256);
}
return new int[][] { parents, weights };
}
}
I attached an image that contains the algorithm that I used.

Problems with my program or netbeans error

I was doing an exercise and in which you ask us the following: Exercise 06: Read the data corresponding to two tables of 12 numerical elements and mix them in a third of the form: 3 from tables A, 3 from B, others 3 of the A, another 3 of the B, Etc. When making the code (according to me it is fine) I get an error in netbeans (attached a photo) can you tell me what is the reason for my error? I'm still a student. In advance thank you very much for reading (I attach my code and the image of the error).
package ejercicioarreglos_06;
import java.util.Scanner;
public class EjercicioArreglos_06 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tablaA[] = new int[12];
int tablaB[] = new int[12];
int contador = 0;
boolean eleccion = true;
int contA = 0, contB = 0;
for (int i = 0; i < tablaA.length; i++) {
System.out.print("Ingresa el valor " + (i + 1) + " de la tabla A: ");
tablaA[i] = in.nextInt();
}
for (int j = 0; j < tablaB.length; j++) {
System.out.print("Ingrese el valor " + (j + 1) + " de la tabla B: ");
tablaB[j] = in.nextInt();
}
for (int k = 0; k < tablaB.length + tablaB.length; k++) {
if (eleccion = true) {
System.out.println(tablaA[contA]);
contador++;
contA++;
if (contador > 2) {
eleccion = false;
}
} else {
System.out.print(tablaB[contB]);
contador--;
contB++;
if (contador < 0) {
eleccion = true;
}
}
}
}
}
According to Javadoc:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ArrayIndexOutOfBoundsException
It is an exception (error) that happens when we provide an index outside the limits allowed for the access of elements in an array. Remember that Java indexes start at 0 and go up to the number of elements -1.
Note the position of the public class ArrayIndexOutOfBoundsException in the class hierarchy of the Java platform:
-> java.lang.Object
--> java.lang.Throwable
---> java.lang.Exception
----> java.lang.RuntimeException
-----> java.lang.IndexOutOfBoundsException
------> java.lang.ArrayIndexOutOfBoundsException
Here is an example where we try to access an element of an array using an invalid index:
public class Test{
public static void main(String args[]){
// an array of five elements
int[] values = {8, 98, 100, 3, 14};
// we will provide an invalid index
System.out.println(values[5]);
System.exit(0);
}
}
This code compiles normally. However, when we try to run it, we get the following error message:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at Study.main(Test.java:7)
The most appropriate way to correct this error is to provide an index value that is really in the allowed range.
The If condition available seems to be true always and I corrected it to make the code work i.e., from if (eleccion = true) to if (eleccion)
package ejercicioarreglos_06;
import java.util.Scanner;
public class EjercicioArreglos_06 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tablaA[] = new int[12];
int tablaB[] = new int[12];
int contador = 0;
boolean eleccion = true;
int contA = 0, contB = 0;
for (int i = 0; i < tablaA.length; i++) {
System.out.print("Ingresa el valor " + (i + 1) + " de la tabla A: ");
tablaA[i] = in.nextInt();
}
for (int j = 0; j < tablaB.length; j++) {
System.out.print("Ingrese el valor " + (j + 1) + " de la tabla B: ");
tablaB[j] = in.nextInt();
}
for (int k = 0; k < tablaB.length + tablaB.length; k++) {
if (eleccion) {
System.out.println(tablaA[contA]);
contador++;
contA++;
if (contador > 2) {
eleccion = false;
}
} else {
System.out.print(tablaB[contB]);
contador--;
contB++;
if (contador < 0) {
eleccion = true;
}
}
}
}
}

Need help : Stack in Vector

I'm doing a project for the university, and I need your help, because I don't find my wish in the API documentation.
I have a class named Belote.java (who simulate a card game).
My professor wants to force us to use the class Stack in a Vector (can't use another class sorry :/ )
Those two method set don't run, I think I know why, but I can't resolve this alone.
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).push(carte));
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).pop());
I put a commentary where the method bug.
package TP.TP5.Exercice2.Question2;
import java.util.Random;
import java.util.Vector;
import java.util.Stack;
import TP.TP5.Exercice1.Question4.Carte;
public class Belote {
private Stack<Carte> tasDistibution;
private Vector<Stack<Carte>> mainsJoueurs;
private Vector<Stack<Carte>> plisJoueurs;
public Belote() {
this.tasDistibution = new Stack<Carte>();
this.mainsJoueurs = new Vector<Stack<Carte>>(4);
this.plisJoueurs = new Vector<Stack<Carte>>(4);
for (int i = 0; i < 4; i++) {
this.mainsJoueurs.add(i, new Stack<Carte>());
this.plisJoueurs.add(i, new Stack<Carte>());
}
}
private void initialiserTasDistribution() {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 13; j++) {
if (j == 1 || (j >= 7 && j <= 13)) {
this.tasDistibution.push(new Carte(i, j));
}
}
}
}
private void couper() {
Stack<Carte> tas1 = new Stack<Carte>();
Stack<Carte> tas2 = new Stack<Carte>();
Random r = new Random();
int coupe = 1 + r.nextInt(33 - 1);
for (int i = 0; i < coupe; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas1.push(carte);
}
while (tasDistibution.isEmpty() == false) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas2.push(carte);
}
while (tas1.isEmpty() == false) {
Carte carte = tas1.peek();
tas1.pop();
this.tasDistibution.push(carte);
}
while (tas2.isEmpty() == false) {
Carte carte = tas2.peek();
tas2.pop();
this.tasDistibution.push(carte);
}
}
private void melanger(int nbMelange) {
Carte tabcarte[] = new Carte[32];
for (int i = 0; i < tabcarte.length; i++) {
Carte cartesommet = this.tasDistibution.peek();
this.tasDistibution.pop();
tabcarte[i] = cartesommet;
}
for (int i = 0; i < nbMelange; i++) {
Random r = new Random();
int pos1 = 1 + r.nextInt(32 - 1);
int pos2 = 1 + r.nextInt(32 - 1);
if (pos1 == pos2) {
System.out.println("Pas de chance");
} else {
Carte temp;
temp = tabcarte[pos1];
tabcarte[pos1] = tabcarte[pos2];
tabcarte[pos2] = temp;
}
}
for (int i = 0; i < tabcarte.length; i++) {
Carte carte = tabcarte[i];
this.tasDistibution.push(carte);
}
}
private void donnerCartesAJoueur(int nbcartedonnes, int numjoueur) {
for (int i = 0; i < nbcartedonnes; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
//My problem is right here, the method set doesn't work, because the method push return a "Carte" and not a "Stack<Carte>"
//The compilateur says : The method set(int, Stack<Carte>) in the type Vector<Stack<Carte>> is not applicable for the arguments (int, Carte)
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).push(carte));
}
}
private void distribuer() {
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(2, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
System.out.println("\n\nDistribution pour joueur : " + (i + 1) + " \n\nMain du joueur : " + (i + 1));
this.mainsJoueurs.get(i).toString();
}
}
private void assemblerPlisJoueur() {
for (int i = 0; i < 4; i++) {
while (this.plisJoueurs.get(i).isEmpty() == false) {
Carte carte = this.plisJoueurs.get(i).peek();
//Same problem here
this.plisJoueurs.set(i, this.plisJoueurs.get(i).pop());
this.tasDistibution.push(carte);
}
}
}
private void preparerPremiereManche() {
this.initialiserTasDistribution();
this.melanger(32);
this.couper();
this.distribuer();
}
private void preparerMancheSuivante() {
this.assemblerPlisJoueur();
this.couper();
this.distribuer();
}
private void jouerPli() {
Stack < Carte > tasIntermediaire = new Stack<Carte>();
for (int i = 0; i < 4; i++) {
Carte carte = this.mainsJoueurs.get(i).peek();
//Same problem here
this.mainsJoueurs.set(i, this.mainsJoueurs.get(i).pop());
tasIntermediaire.push(carte);
}
Random r = new Random();
int gagnant = 0 + r.nextInt(4 - 0);
System.out.println("Le joueur " + (gagnant + 1) + " a gagné ce pli");
for (int i = 0; i < 4; i++) {
Carte carte = tasIntermediaire.peek();
tasIntermediaire.pop();
//Same problem here
this.plisJoueurs.set(gagnant, this.plisJoueurs.get(gagnant).push(carte));
}
System.out.println("Pli du joueur " + (gagnant + 1));
this.plisJoueurs.get(gagnant).toString();
}
private void jouerManche(int nbPlis) {
for (int i = 1; i <= nbPlis; i++) {
System.out.println("\n\nPli numéro : " + i);
this.jouerPli();
}
this.preparerMancheSuivante();
}
public void jouerPartie(int nbManches) {
this.preparerPremiereManche();
for (int i = 1; i <= nbManches; i++) {
System.out.println("\n\nManche numéro : " + i);
this.jouerManche(8);
}
System.out.println("Jeu terminé");
}
}
I don't know how to resolve this problem with using only the class Stack.
Everyone have an idea can be really nice :)
(Sorry for my bad English)
The problem is that you pass in the result of the push method, which is not a Stack<Carte>, but a Carte.
Stack<Carte> stack = this.mainsJoueurs.get(numjoueur);
stack.push(carte); // this returns the added element
this.mainsJoueurs.set(numjoueur, stack);

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

Create a Matrix from an ArrayList

I want to create a class that creates a Matrix via an ArrayList.
So that's what I did:
public class Matrice implements IMatrice {
ArrayList elements;
private int numLignes;
private int numColonnes;
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
public Matrice (int numLignes, int numColonnes, double valeur){
this.numLignes = numLignes;
this.numColonnes = numColonnes;
elements = new ArrayList(numLignes * numColonnes);
for(int i = 0; i < numLignes * numColonnes; i++){
elements.add(i, valeur);
}
}
}
Now that i created this, I wanted to try if it works. Then I created this toString() method:
public String toString() {
final DecimalFormat DEC_FORMAT = new DecimalFormat("0.0");
final int ESP = 8;
int num;
String sTmp;
String s = "[";
for (int i = 0 ; i < (numLignes * numColonnes) ; i++) {
//etendre i sur ESP colonnes
sTmp = "";
num = ESP - DEC_FORMAT.format(elements.get(i)).length();
for (int j = 0 ; j < num ; j++) {
sTmp = sTmp + " ";
}
sTmp = sTmp + DEC_FORMAT.format(elements.get(i));
if (i != 0 && i % numColonnes == 0) {
s = s + " ]\n[" + sTmp;
} else {
s = s + sTmp;
}
}
s = s + " ]";
return s;
}
Then this is my main to try the Matrix:
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
and i don't know why but i only get this :
[ ]
I know that a little thing is wrong but I can't find what. Could you help me?
Okay, i messed up...
The problem was in here :
elements.add(i, valeur);
i did a mistake... i mingled with the set() method.
here is the correction :
elements.add(valeur);

Categories

Resources