Code has incorrect last value in array - java

I can not find why the code has the last incorrect value for test 3 and 5. I can not change the array to array list. The methods are the only thing that I can change.
package Semester;
import java.util.ArrayList;
public class MemberArrayList {
private ArrayList<Integer> friendsScore = new ArrayList<Integer>();
private ArrayList<String> friendsID = new ArrayList<String>();
// Add a friend with ID with the score into friends.
public void addFriend(String friendID, int score) {
// TODO
friendsScore.add(score);
friendsID.add(friendID);
}
// Removes a friend with friendID, but you cannot use indexOf. Only methods you can use: size, equals, get, remove
public void removeFriend(String friendID) {
// TODO
for (int i = 0; i < friendsID.size(); i++)
{
if ( friendID.equals(friendsID.get(i)))
{
friendsScore.remove(i);
friendsID.remove(i);
}
}
}
// Get the scores of first 10 friends added
public int [] getScores10() {
// TODO
int size = 10;
int[] score = new int[size];
for (int i = 0; i < 10; i++)
{
score[i] = friendsScore.get(i);
}
return score;
}
public int [] getScoresLast10() {
// TODO
int[] score = new int[10];
int j = 0;
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
{
score[j] = friendsScore.get(i);
j++;
}
return score;
}
// Get the scores of the friends in the array, but you cannot use indexOf function. You can only use size, get, equals, intValue
public int [] getScores(String [] friendIDs) {
// TODO
int value = friendIDs.length;
int[] score = new int[value];
for (int i = 0; i < value; i++)
{
String person = friendIDs[i];
for (int j = 0; j < friendsID.size(); j++)
{
if (person.equals(friendsID.get(j)))
{
score[i] = friendsScore.get(j);
}
}
}
return score;
}
public static void main(String[] args) {
MemberArrayList member = new MemberArrayList();
member.addFriend("Paul", 3);
member.addFriend("Peter", 1);
member.addFriend("Mary", 2);
member.addFriend("John", 4);
member.addFriend("Karen", 7);
member.addFriend("Kevin", 3);
member.addFriend("Walter", 1);
member.removeFriend("Mary");
member.removeFriend("Walter");
member.addFriend("Steven", 21);
member.addFriend("Kelly", 9);
member.addFriend("Kaitlin", -5);
member.addFriend("Bea", 77);
member.addFriend("Max", 32);
System.out.println("Test 1");
String [] friendIDs = {"Paul","Kevin","Steven","Max"};
int [] scores = member.getScores(friendIDs);
for (int i = 0; i < scores.length; i++)
System.out.println(friendIDs[i]+" "+scores[i]);
System.out.println("Test 2");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 3");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
member.removeFriend("Bea");
member.addFriend("Eric", -1);
member.addFriend("Abby", -2);
member.addFriend("Jacob", 3);
member.addFriend("Blake", 8);
System.out.println("Test 4");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 5");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
}
}
The output should be
Test 1
Paul 3
Kevin 3
Steven 21
Max 32
Test 2
3
1
4
7
3
21
9
-5
77
32
Test 3
32
77
-5
9
21
3
7
4
1
3
Test 4
3
1
4
7
3
21
9
-5
32
-1
Test 5
8
3
-2
-1
32
-5
9
21
3
7

Your loop for counting down is missing one value to copy:
Wrong:
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
This runs for 9 times.
Right:
for (int i = friendsScore.size()-1; i >= (friendsScore.size()-10); i--)
This runs 10 times and copies all 10 values to the array. Note the >= instead of >.
With the first loop the last value of your array will never be set and so defaults to 0 or whatever your compiler might set (I think it is always 0 in java but I'm not sure).

Related

changing value of the last 3 index in an array

i am currently learning java, bellow are my current code
import java.util.*;
public class numbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How big is the array: ");
int size = input.nextInt();
int[] numb = new int[size];
for (int i=0;i<size;i++)
{
numb[i] = i;
}
//change value of last 3 index of array to 0
for (int i =0; i<size;i++)
{
System.out.println(numb[i]);
}
}
}
Here are how the output if i ran it currently
How big is the array: 7
0
1
2
3
4
5
6
how could i change the value of the last 3 index to 0? bellow are my expected output
How big is the array: 7
0
1
2
3
0
0
0
thanks in advance!
You can loop through the last 3 index and set it to 0.
for (int i = 1; i <= 3; i++) {
num[num.length - i] = 0;
}
You mean?
//change value of last 3 index of array to 0
for (int i = size-1; i >= size-3;i--)
{
numb[i] = 0;
}
//OR
for (int i = size-2; i<size;i++)
{
numb[i] = 0;
}
for (int i = 0; i<size;i++)
{
System.out.println(numb[i]);
}
This should do the trick:
//change value of last 3 index of array to 0
if (size <= 3) {
for (int i =0; i<size;i++)
{
numb[i] = 0;
}
} else {
for (int i=size-3; i<size; i++) {
numb[i] = 0;
}
}
Just subtract 3 from the size, it will work perfectly
for (int i=0;i<size-3;i++)
{
numb[i] = i;
}

Print Pascal's Triangle using recursion

I'm trying to develop a program that prints out Pascal's Triangle using recursion. Here are my codes:
public class PascalTriangle {
public static int[] computePT(int k) {
int[] pt = new int[k + 1];
if (k == 0) {
pt[0] = 1;
return pt;
} else {
int[] ppt = computePT(k - 1);
pt[0] = pt[k] = 1;
for (int i = 1; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
}
return pt;
}
}
public class PascalTriangleDriver {
public static void main(String args[]) {
int k = 10;
int arr[] = PascalTriangle.computePT(k);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
The code runs perfectly, however my issue is that I want to modify my PascalTriangle code (not the PascalTriangleDriver code) such that when k=10, for example, it prints out:
1 9 36 84 126 126 84 36 9 1
instead of:
1 10 45 120 210 252 210 120 45 10 1
You seem to have made an off-by-1 error. One simple way to solve this is to write another method that calls your original method with k-1:
// this is your original method, just renamed:
private static int[] computePTImpl(int k) {
int[] pt = new int[k + 1];
if (k == 0) {
pt[0] = 1;
return pt;
} else {
int[] ppt = computePT(k - 1);
pt[0] = pt[k] = 1;
for (int i = 1; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
}
return pt;
}
// you will call this method:
public static int[] computePT(int k) {
return computePT(k - 1);
}
Alternatively, you can actually fix your code by replacing ks with k-1s:
public static int[] computePT(int k) {
int[] pt = new int[k]; // note the change
if (k == 1) { // note the change
pt[0] = 1;
return pt;
} else {
int[] ppt = computePT(k - 1);
pt[0] = pt[k - 1] = 1; // note the change
for (int i = 1; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
}
return pt;
}
Note that we don't change the recursive call because if we did, we would be saying that the k-th row of Pascal's triangle depends on the k-2-th row, which is not true.
You can iteratively populate an array of binomial coefficients as follows: the first row and column are filled with ones, and all other elements are equal to the sum of the previous element in the row and column.
T[i][j] = T[i][j-1] + T[i-1][j];
You can create two methods: one returns a 2d array containing a triangle, and the second returns the base of that triangle. It is more useful for clarity.
Output:
Triangle:
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9
1 3 6 10 15 21 28 36
1 4 10 20 35 56 84
1 5 15 35 70 126
1 6 21 56 126
1 7 28 84
1 8 36
1 9
1
Base:
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Code:
public static void main(String[] args) {
int n = 10;
System.out.println("Triangle:");
int[][] arr = binomialTriangle(n);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
if (arr[i][j] > 0)
System.out.printf("%2d ", arr[i][j]);
System.out.println();
}
int[] base = binomial(arr);
System.out.println("Base:");
System.out.println(Arrays.toString(base));
}
public static int[][] binomialTriangle(int n) {
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
return arr;
}
public static int[] binomial(int[][] arr) {
int[] base = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
// the last element in the row
base[i] = arr[i][arr[i].length - 1];
}
return base;
}
See also: Finding trinomial coefficients using dynamic programming

How to double input of an array in java?

So, I am trying to take an array input of 6,7,34,7,6 and create a method to have the ouput be 6 6 7 7 34 34 7 7 6 6.
How would i go about that?
So far I have:
public int [] twice (int[] ary)
int [] A = new int [ary.length * 2]
A [0] = 6;
A [1] = 7;
A [2] = 34;
A [3] = 7;
A [4] = 6;
But i don't know where to go from there.
Try this one:
public static int[] twice(int[] ary) {
int[] A = new int[ary.length * 2];
for(int i=0, j=0;j<ary.length;i=i+2,j++) {
A[i] = A[i+1] = ary[j];
}
return A;
}
Just use two for loops
{
for (int i=0;i<5;i++) System.print(ary[i]);
for (int i=0;i<5;i++) System.print(ary[4-i]);
}
If u want to add the values at the end
// Java program explaining System class method - arraycopy()
import java.lang.*;
import java.util.Arrays;
public class NewClass
{
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = Arrays.copyOf(s, s.length*2);
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 0;
dest_arr = d;
destPos = s.length;
len = s.length;
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
}
public static int [] twice (int[] ary)
{
int [] A = new int [ary.length * 2];
//take 2 variables one to point input array and 1 for output array
int c = 0;
for(int n: ary) {
//put each element of input array twice in output array
A[c] = A[c+1] = n;
c += 2;
}
//return output array
return A;
}
As your input values look like they're sorted and then you put the same values to destination array again in descending order, you might want to try attempt with sorting your input first depending on what you want to achieve:
public int [] twice(int[] ary) {
int[] temporary = new int[ary.length];
for (int i = 0; i < ary.length; i++) { // copying ary to temporary
temporary[i] = ary[i];
}
Arrays.sort(temporary); // sorting temporary in ascending order
int[] result = new int[ary.length * 2]; // creating double sized result array
for(int i = 0; i < temporary.length; i++) { // copying sorted contents of temporary at the beginning of result array
result[i] = temporary[i];
}
int j = 0 ;
for(int i = result.length - 1; i >= result.length / 2; i--) { // inserting contents of temporary from the end of result array to the middle ("from right to left")
result[i] = temporary[j++];
}
return result; // returning result array
}

Java array removal gives unexpected results?

The following code is part of a program which takes the values of array ar except for variable z, and copies it onto a different array called ar2. The result should be all the numbers except negative two (19, 1, 17, 17), but currently the result is 19 1 17 17 -2 19 1 17 17 -2 19 1 17 17 -2 19 1 17 17 -2.
public class Second_tiny {
public static void main(String[] args) {
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 0; i < (ar.length); i++) {
if (z > ar[i]) {
z = ar[i];
}
}
// second pass
int[] ar2 = new int[ar.length];
int zero = 0;
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
}
/*
* //2nd pass copy all items except smallest one to 2nd array int[] ar2= new int[ar.length-1]; int curIndex = 0; for (i=0; i<ar.length; i++) { if (ar[i]==z) continue; ar2[curIndex++] =
* ar[i]; }
*/
}
}
}
Java 8 way:
int[] ar = { 19, 1, 17, 17, -2 };
int min = Arrays.stream(ar).min().getAsInt();
int[] ar2 = Arrays.stream(ar).filter(s -> s!=min).toArray();
System.out.println(Arrays.toString(ar2));
You're printing out your original array 4 times in this block:
for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
}
That block should be outside of your loop, and should reference ar2 instead of ar.
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
}
for (int i = 0; i < ar2.length; i++) {
System.out.println(ar2[i]);
}
This will give you the following result:
19
1
17
17
0
The last 0 appears because 0 is the default value for ints. Your ar2 array is 5 elements long, and for the last element the default value is never replaced.
You could use Math.min(int, int) to determine your lowest value. Your second array should be one element smaller. I suggest guarding against removing more than one value. And you could use Arrays.toString(int[]) to print the second array. Something like,
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 1; i < ar.length; i++) {
z = Math.min(z, ar[i]);
}
// second pass
int[] ar2 = new int[ar.length - 1];
boolean first = true;
for (int x = 0; x < ar.length; x++) {
if (ar[x] == z && first) {
first = false;
continue; // If it is equal to z go back to the loop again
}
int y = x - (!first ? 1 : 0);
ar2[y] = ar[x];
}
System.out.println(Arrays.toString(ar2));
Output is
[19, 1, 17, 17]
you code is right mistakenly you have given one extra for loop.i have done comment on that for loop.use the following code u will get the desired output.
public class HelloWorld {
public static void main(String[] args) {
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 0; i < (ar.length); i++) {
if (z > ar[i]) {
z = ar[i];
}
}
// second pass
int[] ar2 = new int[ar.length];
int zero = 0,i=0;
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
// for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
i++;
// }
/*
* //2nd pass copy all items except smallest one to 2nd array int[] ar2= new int[ar.length-1]; int curIndex = 0; for (i=0; i<ar.length; i++) { if (ar[i]==z) continue; ar2[curIndex++] =
* ar[i]; }
*/
}
}
}
output is:
19
1
17
17

Java Array sort by means of a comparator

The complete code can be found at: https://skydrive.live.com/redir?resid=7B7D2F11B13EF9C9!54468&authkey=!AD4fD8sGgc7oJIE
This is part of the code:
g_sorted = 0;
for (int l_loop = 0; l_loop < l_length; l_loop++)
{
if (!l_IntegerArray[l_loop].equals(g_exclude))
{
g_tag[g_sorted] = l_loop;
g_tosort_Integer[g_sorted] = l_IntegerArray[l_loop];
g_sorted++;
}
} // for (int l_loop = 0; l_loop < p_toSort; l_loop++)
Arrays.sort
(g_tag, 0, g_sorted, new Comparator<Integer>()
{
public int compare(Integer i1, Integer i2)
{
return Integer.compare(g_tosort_Integer[i1], g_tosort_Integer[i2]);
}
}
);
g_tosort_Integer, g_tag, g_tosort_Integer are 'Integer'.
g_exclude is used to exclude items which must not be part of the sort.
When no items are excluded (no item has the value equal to g_exclude or the if-statement is commented), everything works fine.
When 1 or more items are excluded I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at TestSort$1.compare(TestSort.java:53)
at TestSort$1.compare(TestSort.java:50)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:190)
at java.util.Arrays.sort(Arrays.java:727)
at TestSort.<init>(TestSort.java:48)
at TestSort.main(TestSort.java:71)
Can someone explain this to me ? Thanks.
This is how to solve. I kept your class "structure", but I took the liberty of changing variable names to get clearer what I was doing. You asked how to order an array not changing the order of elements, but changing a index upon it.
Here's the code.
public class TestSort {
int c_maxSort = 10000;
Integer[] unsortedAndFiltered = new Integer[c_maxSort];
Integer[] index = new Integer[c_maxSort];
public TestSort() {
Integer exclude = 0;
int newPosition;
int lengthOfOriginalArray;
Integer[] originalArray = { 5, 3, 0, 2, 7, 1, 5, 6, 8, 4 };
lengthOfOriginalArray = originalArray.length;
System.out.print("Original: ");
for (int i = 0; i < lengthOfOriginalArray; i++)
System.out.print(originalArray[i] + " ");
System.out.println(" - Length: " + lengthOfOriginalArray);
newPosition = 0;
for (int i = 0; i < lengthOfOriginalArray; i++) {
if (!originalArray[i].equals(exclude)) {
index[newPosition] = newPosition;
unsortedAndFiltered[newPosition] = originalArray[i];
newPosition++;
}
}
System.out.println("Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Unsorted numbers: ");
for (int l_loop = 0; l_loop < newPosition; l_loop++)
System.out.print(unsortedAndFiltered[l_loop] + " ");
System.out.println("");
int deleted = lengthOfOriginalArray - newPosition;
Arrays.sort(index, 0, newPosition, new IndirectedComparator(unsortedAndFiltered, index));
System.out.println("Sorted Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Sorted Numbers: ");
for (int i = 0; i < newPosition; i++)
System.out.print(unsortedAndFiltered[index[i]] + " ");
System.out.println("");
}
public static void main(String[] args) {
new TestSort();
}
}
where the comparator is coded like this:
public class IndirectedComparator implements Comparator<Integer> {
private Integer[] array;
private Integer[] index;
public IndirectedComparator(Integer [] array, Integer[] index){
this.array = array;
this.index = new Integer[index.length];
System.arraycopy(index, 0, this.index, 0, index.length);
}
#Override
public int compare(Integer i1, Integer i2) {
return Integer.compare(array[index[i1]], array[index[i2]]);
}
}
This is my execution:
Original: 5 3 0 2 7 1 5 6 8 4 - Length: 10
Tags:
0 1 2 3 4 5 6 7 8
Unsorted numbers:
5 3 2 7 1 5 6 8 4
Sorted Tags:
4 2 1 8 0 5 6 3 7
Sorted Numbers:
1 2 3 4 5 5 6 7 8

Categories

Resources