Remove all elements from array in Java - java

I have a doubt in deleting all elements by number in array of objects in Java, it will not be recommended to use ArrayList, the method works but only that it does not eliminate some elements leaving some elements modified, because of their positions in the array
class Pack
public class Pack {
static int nextNumber = 0;
int number;
String name;
public Pack(String name) {
this.number = ++nextNumber;
this.name = name;
}
#Override
public String toString() {
return "Pack ID:" + number + " - Name: " + name;
}
}
class Container
class Container {
static int nextNumber = 0;
int number;
int qtPack;
Pack[] packs;
public Container() {
this.number = ++nextNumber;
this.qtPack = 0;
this.packs = new Pack[10];
}
public boolean addPack(Pack pack) {
packs[qtPack] = pack;
qtPack++;
return true;
}
public Pack removePack(int numberPack) {
int idx;
Pack removePack = null;
idx = indexOfPackByID(numberPack);
if (idx != -1) {
removePack = packs[idx];
if (removePack != null) {
for (int i = idx; i < qtPack - 1; i++) {
packs[i] = packs[i + 1];
}
qtPack--;
}
}
return removePack;
}
private int indexOfPackByID(int numberPack) {
for (int i = 0; i < qtPack; i++) {
if ((packs[i] != null)
&& (packs[i].number == numberPack)) {
return i;
}
}
return -1;
}
}
class Main
public class Main {
public static void main(String[] args) {
Pack[] packs = new Pack[5];
packs[0] = new Pack("A");
packs[1] = new Pack("B");
packs[2] = new Pack("C");
packs[3] = new Pack("D");
packs[4] = new Pack("E");
Container container = new Container();
for (int i = 0; i < packs.length; i++) {
container.addPack(packs[i]);
}
System.out.println("--- PACK IN CONTAINER ---");
for (int i = 0; i < container.qtPack; i++) {
System.out.println(container.packs[i].toString());
}
System.out.println("\n--- REMOVE PACK ---");
for (int i = 0; i < container.qtPack; i++) {
Pack pack = container.removePack(container.packs[i].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
}
}
the output from Main
--- PACK IN CONTAINER ---
Pack ID:1 - Name: A
Pack ID:2 - Name: B
Pack ID:3 - Name: C
Pack ID:4 - Name: D
Pack ID:5 - Name: E
--- REMOVE PACK ---
Remove A - ID: 1
Remove C - ID: 3
Remove E - ID: 5
any suggestion?

You could either remove them from the end...
for (int i = container.qtPack-1; i >= 0; i--) {
Pack pack = container.removePack(container.packs[i].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
...or always remove the first element:
int count = container.qtPack;
for (int i = 0; i < count; i++) {
Pack pack = container.removePack(container.packs[0].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
This is because by changing the array you are changing the condition (here container.packs and container.qtPack) with each iteration. Keep in mind that the loop condition i < container.qtPack is evaluated for each iteration.

Take a closer look at Container.removePack()
for (int i = idx; i < qtPack - 1; i++) {
packs[i] = packs[i + 1];
}
Each time invoke removePack(), the container references some elements of packs[] to the 'next' Pack. So the packs[] are not the same after removePack().

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.

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);

Assign values to array that have multible variables in java

I had created an array of the following class , when I try to assign new values it gives me null
my code as follows
public class edge {
public double w = 0 ;
public int a = 0 ;
public int b = 0 ;
}
edge edges[];
edges = new edge[5];
int c = 10
for ( int i = 0 , i< 5 , i++) {
edges[i]=new edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i/c ;
}
You have some problems in your code :
First : you should not put your code outside your class like you do
Secondd: you have to use the main method to start your program
Third : you should to separate your statement in your loop with ; and not with , your program should look like this :
public class Edge {
public double w = 0;
public int a = 0;
public int b = 0;
public static void main(String[] args) {
Edge edges[];
edges = new Edge[5];
int c = 10;
for (int i = 0; i < 5; i++) {
edges[i] = new Edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i / c;
}
}
}
Or you can separate them in differentiate classes like this :
public class Cls {
public static void main(String[] args) {
Edge edges[];
edges = new Edge[5];
int c = 10;
for (int i = 0; i < 5; i++) {
edges[i] = new Edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i / c;
}
System.out.println(Arrays.toString(edges));
//Output
//[edge{w=0.0, a=0, b=1}, edge{w=0.0, a=1, b=2}, edge{w=0.0, a=2, b=3}, edge{w=0.0, a=3, b=4}, edge{w=0.0, a=4, b=5}]
}
}
class Edge {
public double w = 0;
public int a = 0;
public int b = 0;
#Override
public String toString() {
return "edge{" + "w=" + w + ", a=" + a + ", b=" + b + '}';
}
}

Insertion sort not working

The sortYears() method should sort the movies by year of release in descending order. It compiles fine, but does not change the order of the movies in the array sorted. What is the least uncomplicated way to fix make it work? Thanks.
Movie2 class:
public class Movie2 implements Comparable<Movie2>
{
// instance variables
private String title;
private int year;
private String studio;
public Movie2(String title, int year, String studio)
{
// initialise instance variables
this.title = title;
this.year = year;
this.studio = studio;
}
public String toString()
{
String listing;
listing = title + ", " + year + ", " + studio;
return listing;
}
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return title;
}
public void setYear(int year)
{
this.year = year;
}
public int getYear()
{
return year;
}
public void setStudio(String studio)
{
this.studio = studio;
}
public String getStudio()
{
return studio;
}
public int compareTo(Movie2 obj)
{
if (title.equals(obj.title))
return -1;
else if (title == obj.title)
return 0;
else
return 1;
}
}
TestMovie2 class:
public class TestMovie2
{
public static void main(String[] args)
{
Movie2[] myMovies = new Movie2[10];
Movie2[] sorted = new Movie2[10];
myMovies[0] = new Movie2("The Muppets Take Manhattan", 2001, "Columbia Tristar");
myMovies[1] = new Movie2("Mulan Special Edition", 2004, "Disney");
myMovies[2] = new Movie2("Shrek 2", 2004, "Dreamworks");
myMovies[3] = new Movie2("The Incredibles", 2004, "Pixar");
myMovies[4] = new Movie2("Nanny McPhee", 2006, "Universal");
myMovies[5] = new Movie2("The Curse of the Were-Rabbit", 2006, "Aardman");
myMovies[6] = new Movie2("Ice Age", 2002, "20th Century Fox");
myMovies[7] = new Movie2("Lilo & Stitch", 2002, "Disney");
myMovies[8] = new Movie2("Robots", 2005, "20th Century Fox");
myMovies[9] = new Movie2("Monsters Inc.", 2001, "Pixar");
System.out.println(" Movies (before change) ");
System.out.println("______________________________");
System.out.println();
printMovies(myMovies);
System.out.println();
System.out.println();
for (int i = 0; i < myMovies.length; i++)
{
int next = myMovies[i].getYear();
int insertIndex = 0;
int k = i;
while (k>0 && insertIndex == 0)
{
if (next > sorted[k-1].getYear())
{
insertIndex = k;
}
else
{
sorted[k] = sorted[k-1];
}
k--;
}
sorted[insertIndex].setYear(next);
}
sortYears(myMovies, sorted);
System.out.println(" Sorted by year - descending");
System.out.println("______________________________");
System.out.println();
printMovies(sorted);
System.out.println();
System.out.println();
public static void printMovies(Movie2[] sorted)
{
for(int i = 0; i < sorted.length; i++)
System.out.println(sorted[i]);
}
public static void sortYears(Movie2[] myMovies, Movie2[] sorted)
{
for ( int i = 0 ; i < myMovies.length ; i++ )
{
Movie2 next = myMovies[ i ];
int insertindex = 0;
int k = i;
while ( k > 0 && insertindex == 0 )
{
if ( next.getYear() > sorted[k-1].getYear() )
{
insertindex = k;
}
else
{
sorted[ k ] = sorted[ k - 1 ];
}
k--;
}
sorted[ insertindex ] = next;
}
You are going about your insertion sort incorrectly. Think about the logic needed to sort from Highest to lowest. This is an insertion sort working with an array, but this works, and can be extrapolated to fit your code.
public static void main(String[] args) {
int [] ar1 = {1, 5, 4, 9, 3, 2, 7, 8, 6, 0};
int temp = 0;
System.out.println ("Unsorted: ");
for (int i = 0; i < ar1.length; i++)
System.out.print (ar1[i] + " ");
for (int i = 1; i < ar1.length; i++) {
temp = ar1[i];
// temp < ar1[j] = Sort in ascending order
for (int j = i - 1; j >= 0 && temp > ar1[j]; j--) {
ar1[j + 1] = ar1[j];
}
ar1[j + 1] = temp;
}
System.out.println ("\nSorted: ");
for (int i = 0; i < ar1.length; i++)
System.out.print (ar1[i] + " ");
}
}

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