Can you make generic structure nullable? - arrays

I implemented a generic structure and wanted it to contain nulls at unassigned indexes so for int array instead of 0 it should contain null, for string array instead of empty string it would be null etc. Can you do that for a generic type?
using System;
using System.Collections;
using System.Collections.Generic;
namespace Name
{
public class DynamicArray<T>
{
private T[] array;
private int count;
private int capacity;
public T this[int i]
{
get { return array[i]; }
set
{
if (i >= capacity)
{
T[] temp = new T[i + 1];
for (int j = 0; j < Capacity; j++)
{
temp[j] = array[j];
}
count = i;
capacity = i;
array = temp;
}
else
count++;
array[i] = value;
}
}
public int Count { get => count; }
public int Capacity { get => capacity; }
public DynamicArray()
{
array = new T[1];
count = 0;
capacity = 1;
}
}

Related

2d array of type Space

I'm trying to make a 9x9 grid of Spaces with 1-10 int values. I'm using the java n-ide app, and am getting a successful compilation, but it's not printing any values.
class Space {
int one = 1;
int two = 2;
...
int ten = 10;
}
class green {
Space[][] board = new Space[9][9];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = new Space();
System.out.println(board[i][j].one);
}
}
}
I think you can just refactor your Space class to just hold a primitive integer value:
class Space {
private int value;
private static final String MSG = "Space values must be between 1 and 10 inclusive";
public Space() { }
public Space(int value) {
// prevent spaces from being created with illegal values
if (value < 1 || value > 10) {
throw new IllegalArgumentException(MSG);
}
this.value = value;
}
public int getValue() {
return value;
}
}
Then, in your consuming class, use the Space class:
class Green {
private Space[][] board = new Space[9][9];
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[i].length; j++) {
// maybe get a value from somewhere and use it below
board[i][j] = new Space();
}
}
}
Regarding your exact question about values not printing, the bigger problem than above is that you don't have any logic for assigning values.

Selection Sort for strings and integers at the same time

Here is the task I have been set with:
Create a text file named Names_ages.txt with the following content:
Jones 14
Abrams 15
Smith 19
Jones 9
Alexander 22
Smith 20
Smith 17
Tippurt 42
Jones 2
Herkman 12
Jones 11
Each line is a person’s last name followed by a space and then his age. We want to sort these names alphabetically and in the case of duplicate names, sort by age in an ascending fashion. A properly sorted list will appear as follows:
Abrams, 15
Alexander, 22
Herkman, 12
Jones, 2
Jones, 9
Jones, 11
Jones, 14
Smith, 17
Smith, 19
Smith, 20
Tippurt, 42
Here are my (working) selection sort methods for Strings and ints respectively:
private static void sort(String[] a) {
String min;
int minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j].charAt(0) < min.charAt(0)) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
private static void sort(int[] a) {
int min, minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j] < min) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
I can sort the names in the text file and then the numbers after, but the ages end up corresponding with incorrect people. Here is my class with the main method:
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges.txt"));
String text[] = new String[100];
int index = 0;
while (scanner.hasNext()) {
text[index++] = scanner.nextLine();
}
scanner.close();
String name;
String[] names = new String[index];
int age;
int[] ages = new int[index];
for (int i = 0; i < index; i++) {
Scanner line = new Scanner(text[i]);
name = line.next();
names[i] = name;
age = line.nextInt();
ages[i] = age;
}
sort(names);
sort(ages);
for (int i = 0; i < index; i++) {
System.out.println(names[i] + ", " + ages[i]);
}
Any help is appreciated, thanks.
Create a POJO class Person implementing Comparable<Person>
After parsing, store Person instances in a collection, say List<Person>
Sort the collection
-
public class PersonTest {
static class Person implements Comparable<Person> {
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName)
.thenComparingInt(Person::getAge);
final String name;
final int age;
public static Person parse(String rec) {
final String[] parts = rec.split(" ");
return new Person(parts[0], Integer.valueOf(parts[1]));
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public int compareTo(Person o) {
return COMPARATOR.compare(this, o);
}
}
#Test
public void testSorting() throws Exception {
final Person[] sortedPersons = Files.lines(Paths.get("/path/to/file.txt"))
.map(Person::parse)
.sorted() // sort it here
.toArray(Person[]::new);
// or instead, sort it here with your custom algorithm
// using Person.COMPARATOR for comparison
}
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges"));
String[] text = new String[100];
int index = -1;
while (scanner.hasNext()) {
text[++index] = scanner.nextLine();
}
scanner.close();
Scanner line;
String[] name = new String[100];
int[] age = new int[100];
for (int i = 0; i <= index; i++) {
line = new Scanner(text[i]);
name[i] = line.next();
age[i] = line.nextInt();
}
String minName;
int minAge;
int minIndex;
for (int i = 0; i <= index; i++) {
minName = name[i];
minAge = age[i];
minIndex = i;
for (int j = i + 1; j <= index; j++) {
if (name[j].compareTo(minName) == 0) {
if (age[j] < minAge) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
} else if (name[j].compareTo(minName) < 0) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
}
name[minIndex] = name[i];
name[i] = minName;
age[minIndex] = age[i];
age[i] = minAge;
}
for (int j = 0; j <= index; j++) {
System.out.println(name[j] + ", " + age[j]);
}
}

Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.
import java.util.Comparator;
public class test
{
public int x[];
public test(int x[])
{
}
public void setx(int newx[])
{
x = newx;
}
public int[] getx()
{
return x;
}
public int findSmallest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] < temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public int findLargest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] > temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public double findMean()
{
int i = 0;
double sum = 0.0;
double avg = 0.0;
while (i < x.length)
{
sum += x[i];
i++;
}
avg = sum / x.length;
return avg;
}
public int findTotal()
{
int i = x.length;
return i;
}
public static void main (String args[])
{
int[] ia = {1, 2, 3, 4, 5, 6};
test intTest = new test(ia);
System.out.println(intTest.findTotal());
}
}
Any help on how to fix this would be amazing.
You forgot use the setx method in the constructor. You're passing the integer array to constructor but not actually initializing the integer array inside the class. You can do this by calling the setx method in your constructor and passing the integer array x to setx method.
Hope this helps.

How can I store the results of permutation in a 2D array?

I need help writing this code to get the permutation of numbers.
I need to store all the permutations in a 2D array.
After output of the permutation, I then need to process 30 percent of the permutations in one method an the the rest in another method.
My code:
public class Permutation {
* #param args the command line arguments
*/
void printArray(int []a) {
for (int i = 0; i< a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("");
}
void permute(int []a,int k ) {
if(k==a.length)
printArray(a);
else
for (int i = k; i< a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3,4,5,6};
p.permute(a, 2);
}
}
This is my solution instead of a 2d array use an ArrayList
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* #author David
*/
public class Permutations {
public static int[] a;
public final int SIZE = 6;
public final int NUMPERM;
public final ArrayList<int[]> newlist;
public Permutations()
{
a = new int[SIZE];
for(int x = 0; x < SIZE; x++)
a[x] = x+1;
NUMPERM = Factorial(a.length);
newlist = new ArrayList<>(NUMPERM);
}
public void permute()
{
permutation(a,0,a.length);
}
private void permutation(int array[],int start, int end)
{
newlist.add(saveArray(array));
if (start<end)
{
int i,j;
for(i=end-2; i>=start; i--)
{
for(j=i+1; j<end; j++)
{
Swap(array,i,j);
permutation(array,i+1,end);
}
Rotate_Left(array,i,end);
}
}
}
private int[] saveArray(int[] array)
{
int[] newarray = new int[array.length];
System.arraycopy(array, 0, newarray, 0, array.length);
return newarray;
}
public void Print()
{ //just to prove the list works
System.out.println("the current size of newlist is : " + newlist.size());
int[] array = new int[a.length];
for(int x = 0; x < newlist.size(); x++)
{
array = newlist.get(x);
System.out.println(Arrays.toString(array));
}
}
private void Swap(int array[],int i,int j)
{
int t;
t = array[i];
array[i] = array[j];
array[j] = t;
}
private void Rotate_Left(int array[],int start,int end)
{
int tmp = array[start];
for (int i=start; i < end-1; i++)
{
array[i] = array[i+1];
}
array[end-1] = tmp;
}
private int Factorial(int a)
{
int fact = 1;
for(int x = a; x > 0; x++)
fact *= a;
return fact;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Permutations newperm = new Permutations();
newperm.permute();
newperm.Print();
}
}
then all you have to do is send the list to the other functions and only use what you need from it.

Customizing TwoDArrayWritable in Hadoop and Not able to iterate the same in reducer

Trying to emit 2 double dimensional array as value from mapper.
In hadoop we have TwoDArrayWritable which takes 1 - 2D array as input.
In order to achieve my usecase, I tried to edit TwoDArrayWritable to take input of 2 - 2D array
/**
* A Writable for 2D arrays containing a matrix of instances of a class.
*/
public class MyTwoDArrayWritable implements Writable {
private Class valueClass;
private Writable[][] values;
private Class valueClass1;
private Writable[][] values1;
public MyTwoDArrayWritable(Class valueClass,Class valueClass1) {
this.valueClass = valueClass;
this.valueClass1 = valueClass1;
}
public MyTwoDArrayWritable(Class valueClass, DoubleWritable[][] values,Class valueClass1, DoubleWritable[][] values1) {
this(valueClass, valueClass1);
this.values = values;
this.values1 = values1;
}
public Object toArray() {
int dimensions[] = {values.length, 0};
Object result = Array.newInstance(valueClass, dimensions);
for (int i = 0; i < values.length; i++) {
Object resultRow = Array.newInstance(valueClass, values[i].length);
Array.set(result, i, resultRow);
for (int j = 0; j < values[i].length; j++) {
Array.set(resultRow, j, values[i][j]);
}
}
return result;
}
/**
* #return the valueClass
*/
public Class getValueClass() {
return valueClass;
}
/**
* #param valueClass the valueClass to set
*/
public void setValueClass(Class valueClass) {
this.valueClass = valueClass;
}
/**
* #return the values
*/
public Writable[][] getValues() {
return values;
}
/**
* #param values the values to set
*/
public void setValues(DoubleWritable[][] values,DoubleWritable[][] values1) {
this.values = values;
this.values = values1;
}
/**
* #return the valueClass1
*/
public Class getValueClass1() {
return valueClass1;
}
/**
* #param valueClass1 the valueClass1 to set
*/
public void setValueClass1(Class valueClass1) {
this.valueClass1 = valueClass1;
}
/**
* #return the values1
*/
public Writable[][] getValues1() {
return values1;
}
public void readFields(DataInput in) throws IOException {
// construct matrix
values = new Writable[in.readInt()][];
for (int i = 0; i < values.length; i++) {
values[i] = new Writable[in.readInt()];
}
// construct values
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
Writable value; // construct value
try {
value = (Writable) valueClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e.toString());
} catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
value.readFields(in); // read a value
values[i][j] = value; // store it in values
}
}
}
public void write(DataOutput out) throws IOException {
out.writeInt(values.length); // write values
for (int i = 0; i < values.length; i++) {
out.writeInt(values[i].length);
}
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
values[i][j].write(out);
}
}
}
}
And emited 2 2D double array from mapper.
MyTwoDArrayWritable array = new MyTwoDArrayWritable (DoubleWritable.class,DoubleWritable.class);
DoubleWritable[][] myInnerArray = new DoubleWritable[EtransEkey.length][EtransEkey[0].length];
DoubleWritable[][] myInnerArray1 = new DoubleWritable[EtransDevalue.length][EtransDevalue[0].length];
// set values in myInnerArray
for (int k1 = 0; k1 < EtransEkey.length; k1++) {
for(int j1=0;j1< EtransEkey[0].length;j1++){
myInnerArray[k1][j1] = new DoubleWritable(EtransEkey[k1][j1]);
}
}
for (int k1 = 0; k1 < EtransDevalue.length; k1++) {
for(int j1=0;j1< EtransDevalue[0].length;j1++){
myInnerArray1[k1][j1] = new DoubleWritable(EtransDevalue[k1][j1]);
}
}
array.set(myInnerArray,myInnerArray1);
Showing error in array.set(myInnerArray,myInnerArray1);
/*
* The method set(DoubleWritable[][], DoubleWritable[][]) is undefined for the type MyTwoDArrayWritableritable
*/
EDIT: How to iterate through these values in Reducer to get myInnerArray matrix and myInnerArray1 matrix?
So far what I did is
for (MyTwoDArrayWritable c : values) {
System.out.println(c.getValues());
DoubleWritable[][] myInnerArray = new DoubleWritable[KdimRow][KdimCol];
for (int k1 = 0; k1 < KdimRow; k1++) {
for(int j1=0;j1< KdimCol;j1++){
myInnerArray[k1][j1] = new DoubleWritable();
}
}
But how to store them back to a double array?
You have not defined the set method in MyTwoDArrayWritable, that is why that error is shown. Instead of calling array.set, you should use the method you have already defined which does exactly what you need: setValues, so replace
array.set(myInnerArray,myInnerArray1);
with
array.setValues(myInnerArray,myInnerArray1);

Resources