I made a map by arraylist, and trying to swap the index(not the value) of arraylist.
For example, the swapRow(1,2) changes the position of row 1 and 2.
This works at the first time, but if I do it again, an error comes out.(Same problem with the swapCol() part.)
Stuck in this problem and need help...
In addition, can anyone help me out making the swapValue() method.
Changing the value is simple, though I also want to move the index, not the value.
import java.text.DecimalFormat;
import java.util.ArrayList;
public class IntMap {
class Data {
private int data_;
public Data(int data)
{
setData(data);
}
public void setData(int data)
{
if(data<0)data=0;
if(data>99)data=99;
data_=data;
}
public int getData()
{
return data_;
}
}
class Index {
private int index_;
public Index(int index)
{
setIndex(index);
}
public void setIndex(int index)
{
if(index < 0) index=0;
index_=index;
}
public int getIndex()
{
return index_;
}
}
private ArrayList<ArrayList<Data>> datas_;
private ArrayList<Index> cols_;
private ArrayList<Index> rows_;
public IntMap(int rowCount, int colCount)
{
if(rowCount < 0) rowCount = 1;
if(rowCount < 0) colCount = 1;
cols_ = new ArrayList<Index>();
rows_ = new ArrayList<Index>();
datas_ = new ArrayList<ArrayList<Data>>();
for(int i=0 ; i<rowCount ; ++i) rows_.add(new Index(i));
for(int i=0 ; i<colCount ; ++i) cols_.add(new Index(i));
for(int i=0 ; i< rowCount ; ++i)
{
ArrayList<Data> temp = new ArrayList<Data>();
datas_.add(temp);
for(int j=0 ; j<colCount ; ++j)
{
temp.add(new Data(0));
}
}
}
public int getValue(int row, int col)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
return datas_.get(rIndex).get(cIndex).getData();
}
public void setValue(int row, int col, int value)
{
int rIndex = getRowIndex(row);
int cIndex = getColIndex(col);
datas_.get(rIndex).get(cIndex).setData(value);
}
public void setRandomValue()
{
for(int row=0 ; row < datas_.size() ; ++row)
{
ArrayList<Data> temp = datas_.get(row);
for(int col=0; col <temp.size() ; ++col)
{
Data data = temp.get(col);
data.setData((int)(Math.random()*100));
}
}
}
public void log()
{
DecimalFormat df = new DecimalFormat("00");
for(int row=0; row<rows_.size(); ++row)
{
for(int col=0; col<cols_.size(); ++col)
{
int value = getValue(row, col);
System.out.print(df.format(value));
if(col<cols_.size()-1)
System.out.print(", ");
}
System.out.println();
}
System.out.println();
}
private int getColIndex(int col)
{
if(col <0 || col>=cols_.size())
{
System.out.println("[error][IntMap][getColIndex] - col is"+col);
return 0;
}
for(int i =0; i<cols_.size(); ++i)
{
if(cols_.get(i).getIndex()==col)
return i;
}
System.out.println("[error][IntMap][getColIndex] - unknown error");
return 0;
}
private int getRowIndex(int row)
{
if(row <0 || row>=rows_.size())
{
System.out.println("[error][IntMap][getRowIndex] - row is"+row);
return 0;
}
for(int i =0; i<rows_.size(); ++i)
{
if(rows_.get(i).getIndex()==row)
return i;
}
System.out.println("[error][IntMap][getRowIndex] - unknown error");
return 0;
}
public void swapValue(int a, int b, int c, int d)
{
//
}
public void swapCol(int a, int b)
{
int col1=a;
int col2=b;
int t=a;
cols_.get(col1).setIndex(col2);
cols_.get(col2).setIndex(t);
}
public void swapRow(int a, int b)
{
int t=a;
rows_.get(a).setIndex(b);
rows_.get(b).setIndex(t);
}
public static void main(String[] args)
{
System.out.println("start!");
IntMap map =new IntMap(3,4);
System.out.println("Init map 3x4");
map.log();
System.out.println("random map");
map.setRandomValue();
map.log();
System.out.print("get map[0][1]= ");
System.out.println(map.getValue(0,1));
System.out.println("set map[2][1]=50");
map.setValue(2, 1 ,50);
map.log();
System.out.println("swap(0,1 <-> 2,1)");
map.swapValue(0,1,2,1);
map.log();
System.out.println("swapRow(0 <-> 2)");
map.swapRow(0,2);
map.log();
System.out.println("swapRow(1 <-> 2)");
map.swapRow(1,2);
map.log();
System.out.println("swapCol(0 <-> 3)");
map.swapCol(0,3);
map.log();
}
}
I think you got confused the index of rows_ arrayList and your Index type. your swapRow(a,b) should check rows_ list and find out the element (Index Object) .getIndex = a and b, then swap the two Index elements, not just like what you did in your method. If you change the method into followings, it should work. you could do some error handling, e.g. what happend parameter a or b invalid. I just set themt to 0.
public void swapRow(int a, int b) {
int ai = 0, bi = 0;
for (final Index i : rows_) {
if (i.getIndex() == a) {
ai = rows_.indexOf(i);
}
if (i.getIndex() == b) {
bi = rows_.indexOf(i);
}
}
final Index aidx = rows_.get(ai);
rows_.set(ai, rows_.get(bi));
rows_.set(bi, aidx);
}
and, i don't know your exact requirment. but from the design point of view, there might be room to improve.
Related
//Whenever I run the code, it keeps giving me the same error. I don't understand why. The union array function's loop also isn't looping completely, likely a problem with the string index out of bound.
//I've tried to change the original function isNumberInArray, but still doesn't work.
package HW;
public class HW_5 {
public static boolean isNumberInArray(int number_check, int array[]) {
for (int value : array) {
value -= 1;
if (number_check == array[value]) {
return true;
}
}
return false;
}
public static int highestlength(int array_1[]) {
int max = array_1[0];
for (int counter = 1; counter < array_1.length; counter++) {
if (array_1[counter] > max) {
max = array_1[counter];
}
}
return max;
}
public static int [] unionArrays(int [] array_1, int [] array_2) {
int array_index_counter = 0;
int highest_1 = highestlength(array_1);
int highest_2 = highestlength(array_2);
int[] union_array = new int[array_1.length + array_2.length];
if (highest_1 > highest_2) {
for (int value_1 : array_1) {
if (isNumberInArray(value_1, array_1) && isNumberInArray(value_1, array_2)) {
union_array[array_index_counter] = value_1;
array_index_counter += 1;
} else {
for (int value_2 : array_2) {
if (isNumberInArray(value_2, array_1) && isNumberInArray(value_2, array_2)) {
union_array[array_index_counter] = value_2;
array_index_counter += 1;
}
}
}
}
}
printArray(union_array);
return union_array;
}
public static void printArray(int array[]) {
for (int value : array) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] Args) {
int list_1[] = {1, 2, 3};
int list_2[] = {1, 3, 5};
System.out.println(isNumberInArray(0, list_1));
System.out.println(unionArrays(list_1, list_2));
}
}
I expected the output to be 1 2 3 5, but the actual output is 0 0 0 0.
For a start the looping in isNumberInArray is strange, try
public static boolean isNumberInArray(int number_check, int array[]) {
for (int value : array) {
if (number_check == value) {
return true;
}
}
return false;
}
Probably because of this your if statements in unionArrays are always false
I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}
use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.
I have made a function for objects to reserve seats in a area. But if 2 objects enter the function at the same time they get the same seats. How do I solve this?
The Function getFreeChairs, returns the chair positions. And sets the Fan. But if two fans enter it at the same time they both get the same seats.
Sven
package model;
import actors.Fan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sveno on 12-10-2016.
*/
public class Vak {
private static int autoId = 1;
private String naam;
private int rijen, stoelenperrij, id;
private List<ArrayList> rows = new ArrayList<>();
private Fan fan = null;
public Vak(String naam, int rijen, int stoelenperrij) {
this.naam = naam;
this.rijen = rijen;
this.stoelenperrij = stoelenperrij;
this.id = autoId;
autoId++;
for (int i = 0; i < rijen; i++) {
rows.add(new ArrayList<Fan>());
}
for (ArrayList row : rows) {
for (int j = 0; j < stoelenperrij; j++) {
row.add(fan);
}
}
}
public void removeReserved(int rij, List<Integer> stoelen){
for (int i = 0; i < stoelen.size()-1; i++) {
//De reserveer alle stoelen
ArrayList<Fan> stoel = rows.get(rij);
stoel.set(stoelen.get(i),fan);
}
}
public int getRijen() {
return rijen;
}
public int getStoelenperrij() {
return stoelenperrij;
}
public List<ArrayList> getRows() {
return rows;
}
public int[] getFreeChairs(int aantalStoelen, Fan fan){
//Check for free seats
int count = 1;
int[] stoelenleeg = new int[aantalStoelen+1];
for (int j = 0; j < rows.size(); j++) {
for (int k = 0; k < rows.get(j).size(); k++) {
if (rows.get(j).get(k) == null){
stoelenleeg[count-1] = k;
count++;
//Not enough seats next to each other
if(count==aantalStoelen+1){
stoelenleeg[aantalStoelen] = j+1;
for (int o = 0; o < stoelenleeg.length-1; o++) {
ArrayList<Fan> stoel = rows.get(j);
stoel.set(stoelenleeg[o],fan);
}
return stoelenleeg;
}
}else{
//Not enough seats
stoelenleeg = new int[aantalStoelen+1];
count=1;
}
}
}
return stoelenleeg;
}
}
If your code is used in a concurrent context (multiple threads), you need to make sure that your code is thread safe.
It means that, only one single thread(person) should be able to call the getFreeChairs function(reserve a seat at a time)
The easy way to do it in java is to use the synchronized key word in the method definition:
public synchronized int[] getFreeChairs(int aantalStoelen, Fan fan){
...
}
I am trying to implement a matrix using a hash map but I think I am doing something wrong somewhere.
If I type the following matrix:
4 3
2 1
I get
0 3
0 0
Here's my code:
package matrix;
import java.util.HashMap;
public class SparseMatrix extends AbstractMatrix{
private int x=0; // nr of rows
private int y=0; // nr of columns
private int hashvalue = 0;
public void Index (final int x, final int y)
{
this.x=x;
this.y=y;
hashvalue=((x+"")+(y+"")).hashCode();
}
public boolean equals (final Object obj)
{
if (obj instanceof Index)
{
Index index = (Index) obj;
return ((x==index.x) && (y==index.y));
}
else
return false;
}
public int hashCode()
{
return hashvalue;
}
private int rows;
private int columns;
private HashMap<Index,Double> values;
private boolean validIndex (final int row, final int column)
{
return (row>=0 && row<rows && column>=0 && column<columns);
}
public SparseMatrix(double[][] contents) throws MatrixException {
this(contents.length,contents[0].length);
for (int i=0; i<contents.length; i++)
for (int j=0; j<contents[0].length; j++)
setElement(i,j,contents[i][j]);
}
public SparseMatrix(int rows, int columns) throws MatrixException {
if (rows<1 || columns<1)
throw new MatrixException("Number of rows and columns cannot be less than 1");
this.rows=rows;
this.columns=columns;
this.values=new HashMap<Index,Double>();
}
#Override
public int getNumberOfRows() {
return rows;
}
#Override
public int getNumberOfColumns() {
return columns;
}
#Override
public double getElement(int row, int column) throws MatrixException {
if (!validIndex(row,column))
throw new MatrixException (row,column);
Index index = new Index (row,column);
if (values.containsKey(index))
return values.get(index);
else
return 0;
}
#Override
public void setElement(int row, int column, double value) throws MatrixException {
if (!validIndex(row,column))
throw new MatrixException (row,column);
Index index = new Index(row,column);
if (value==0)
{
if (values.containsKey(index))
values.remove(index);
}
else
values.put(index,value);
}
}
and my main function:
a2 = new SparseMatrix(2,2);
a1.setElement(0,0,4);
a1.setElement(0,1,3);
a1.setElement(1,0,2);
a1.setElement(1,1,1);
for (int i=0; i<a2.getNumberOfRows(); i++)
{
for (int j=0; j<a2.getNumberOfColumns(); j++)
System.out.print (a2.getElement(i, j)+ " ");
System.out.println();
}
Any ideas what I am doing wrong?
public void Index (final int x, final int y)
It looks like this was supposed to be a constructor of the Index class, but instead it's a method, and I don't see the Index class declared anywhere.
You are assigning an instance of SparseMatrix to a2, but call setElement for a1 :
a2 = new SparseMatrix(2,2);
a1.setElement(0,0,4);
a1.setElement(0,1,3);
a1.setElement(1,0,2);
a1.setElement(1,1,1);
I tried your code, fixing all the compilation errors and not relying on the AbstractMatrix super class (by removing the #Override from all the overridden method and by changing the code at the top of your class into a nested class named Index), and got the desired output :
4.0 3.0
2.0 1.0
Here's the nested Index class I used :
static class Index {
private int x=0; // nr of rows
private int y=0; // nr of columns
private int hashvalue = 0;
public Index (final int x, final int y)
{
this.x=x;
this.y=y;
hashvalue=((x+"")+(y+"")).hashCode();
}
public boolean equals (final Object obj)
{
if (obj instanceof Index)
{
Index index = (Index) obj;
return ((x==index.x) && (y==index.y));
}
else
return false;
}
public int hashCode()
{
return hashvalue;
}
}
I think your constructor should refer to contents[i] instead of contents[0]
public SparseMatrix(double[][] contents) throws MatrixException {
this(contents.length,contents[0].length);
for (int i=0; i<contents.length; i++)
for (int j=0; j<contents[i].length; j++)
setElement(i,j,contents[i][j]);
}
So I have to create a program where I use polymorphism and inheritance to create arrows that point left and arrow and I did that. however, when I created my main class and try to invoke the methods, say for example "LeftArrow.drawHere" to draw the arrow i get errors saying I cannot make a static reference to the non static field "drawHere() from the class LeftArrow". I was wondering then if I can't do that how can I design my main method so it draws the arrows?
here is my code, note that there are several classes but I will post all of them here.
import java.util.Scanner;
public class LeftArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public LeftArrow()
{
super();
tail = 0;
width = 0;
}
public LeftArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth);
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
//System.out.println();
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset());
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside + 1));
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawTail()
{
skipSpaces(getOffset() - getInside() - 1);
System.out.print('*');
skipSpaces(getInside());
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside - 1));
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset());
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
#Override
public void setOffset(int noff) {
// TODO Auto-generated method stub
}
#Override
public int getOffset() {
// TODO Auto-generated method stub
return 0;
}
}
import java.util.Scanner;
public class RightArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public RightArrow()
{
super();
tail = 0;
width = 0;
}
public RightArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth); // must be odd
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
System.out.println();
}
public void drawTail()
{
skipSpaces(getOffset() + 1);
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
skipSpaces(getInside());
System.out.print('*'); // fix
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset() + tail);
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset() + tail);
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
}
public abstract class ShapeBase implements ShapeInterface {
private int offset;
public abstract void drawHere();
public void drawAt(int lineNumber) {
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
}
public class ShapeBasic implements ShapeInterface
{
private int offset;
public ShapeBasic()
{
offset = 0;
}
public ShapeBasic( int noff)
{
offset = noff;
}
public void setOffset(int noff)
{
offset = noff;
}
public int getOffset()
{
return offset;
}
public void drawAt(int linnumber)
{
for (int count = 0; count < linnumber; count++)
System.out.println();
drawHere();
}
public void drawHere()
{
for (int count = 0; count < offset; count++)
System.out.print(' ');
System.out.println('*');
}
}
public interface ShapeInterface
{
public void setOffset(int noff); // set how many space from left
public int getOffset(); // returns offset
public void drawAt(int linnumber); // moves down equal to line number Ex. 5 = 5 down
public void drawHere(); // draws shape after moving left equal to offset
}
I'd ask to see your main method, but I don't have the reputation.
At a guess, I'd say maybe you are not actually instantiating objects of these classes in your main method, but trying to call the methods from them. If, for instance, you do this:
LeftArrow lArrow = new LeftArrow();
lArrow.drawHere();
it should work.
The method drawHere is declared as non-static. Instead of LeftArrow.drawHere() you should call
LeftArrow left = new LefArrow(a, b, c);
left.drawHere();
main is static. It needs to create instances of LeftArrow before it can use them. Something like this:
LeftArrow myArrow = new LeftArrow();
myArrow.drawHere();