This is the given question:
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
This is my code:
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for( int i = length - 1; i >=0; i-- ){
int val = A.get(i) + carry;
result.add(0,val % 10);
carry = val / 10;
}
if (carry == 1){
result.add(0,1);
}
for (int j = 0; j < result.size(); j++){
if(result.get(j).equals(0))
result.remove(j);
else
break;
}
return result;
}
}
However, in the test case:
A : [ 0, 6, 0, 6, 4, 8, 8, 1 ]
it says my function returns
6 6 4 8 8 2
while the correct answer is
6 0 6 4 8 8 2
I have no idea what is wrong with my code.
Thanks!
if(result.get(j).equals(0))
result.remove(j);
else
break;
This will fail if every other index contains a 0. Here's what happens:
0 6 0 6 4 8 8 2
^ (j = 0)
The 0 will be removed, and j is incremented by one.
6 0 6 4 8 8 2
^ (j = 1)
Then this 0 is removed as well, skipping the first 6 in your array. To fix this, change the snippet to:
if(result.get(j).equals(0))
result.remove(j--);
else
break;
This compensates for when an index is removed so that j will not skip the number immediately after any removed 0s.
Check out a similar question at Looping through and arraylist and removing elements at specified index
simpler to do just
while (!result.isEmpty() && result.get(0).equals(0)) {
result.remove(0);
}
This will keep removing the left most 0 until there is no more left most zero to be deleted.
Your last for loop is removing 0 from your result ArrayList<Integer>. After removing that loop, you will get perfect output
public static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for (int i = length - 1; i >= 0; i--) {
int val = A.get(i) + carry; //2 8
result.add(0, val % 10); // 2 8
carry = val / 10;
}
if (carry == 1) {
result.add(0, 1);
}
// for (int j = 0; j < result.size(); j++) {
// if (result.get(j).equals(0))
// result.remove(j);
// else
// break;
// }
for (boolean isZero = true; isZero; ) {
isZero = result.get(0).equals(0);
if(isZero)
result.remove(0);
}
return result;
}
Related
I have created a method, which is supposed to return a growing number list when entered any number.
For example:
input: 5
expected output: [1, 2 2, 3 3 3, 4 4 4 4, 5 5 5 5 5]
current output : [1 , 2 2 , 3 3 3 , 4 4 4 4 , 5 5 5 5 5 ]
input: 2
expected output: [1, 2 2]
current output : [1 , 2 2 ]
How do I delete the white spaces?
This is my code:
ArrayList < String > maxarray = new ArrayList < String > ();
int i, j;
String num = "";
for (i = 1; i <= max; i++) {
num = "";
for (j = 1; j <= i; j++) {
num = num + i + " ";
}
//System.out.print(i);
maxarray.add(num);
}
return maxarray;
I have tried: num= num.replace(" ","");
num = num.replace(" ", "");
but, they don't seem work.
and if I try to convert it into a string, I get the following output: 1 2 2 3 3 3
Help me, please
Easy and short-sighted solution: just trim the string before adding it to the ArrayList:
maxarray.add(num.trim());
With this change the output is:
[1, 2 2, 3 3 3, 4 4 4 4, 5 5 5 5 5]
trim() removes trailing spaces (and leading, had there been any), but not the spaces between the numbers.
Produce correct output from the outset: However, rather than producing not-quite-right output and then correcting it it’s probably less confusing in the end to produce correct output from the outset. That is, without the space after the last number. This is also what the answer by Berto99 does. My preferred way of doing this is: take one iteration out of the inner loop and refrain from adding the space there.
for (i = 1; i <= max; i++) {
num = "";
for (j = 1; j < i; j++) { // stop one number before i
num = num + i + " ";
}
num = num + i; // add no space here
maxarray.add(num);
}
Output still is:
[1, 2 2, 3 3 3, 4 4 4 4, 5 5 5 5 5]
I find this way easier to read than the version with the extra if statement in the answer by Berto99.
For the sake of precision: maxarray is not an int array, it as an ArrayList of strings. And what we needed to trim was not the ArrayList but each string in it.
PS Stream version: For readers who know and like streams here’s a stream version. If you don’t want to learn about streams yet, just ignore.
List<String> maxarray = IntStream.rangeClosed(1, max)
.mapToObj(i -> IntStream.rangeClosed(1, i)
.mapToObj(j -> String.valueOf(i))
.collect(Collectors.joining(" ")))
.collect(Collectors.toList());
One of the convenient things is that Collectors.joining(" ") puts spaces between the numbers without putting any space before the first or after the last, which solves the problem asked about.
As you can see from here:
ArrayList < String > maxarray = new ArrayList < String > ();
int i, j;
String num = "";
for (i = 1; i <= max; i++) {
num = "";
for (j = 1; j <= i; j++) {
num = num + i + " ";
^^^^-- here
}
//System.out.print(i);
maxarray.add(num);
}
return maxarray;
you add a space after every number, so you only need to check if you are not in the last number, in order not to add the space in that case:
ArrayList < String > maxarray = new ArrayList < String > ();
int i, j;
String num = "";
for (i = 1; i <= max; i++) {
num = "";
for (j = 1; j <= i; j++) {
num = num + i;
if(j < i) // <--- check if you are not in the last iteration
num = num + " ";
}
//System.out.print(i);
maxarray.add(num);
}
return maxarray;
Sample input:
45 8 4 10 44 43 12 9 8 2
First number = N
Second number = T
Following T numbers = A set of values
My job is to find the subset where the sum is the highest possible one out of all subsets, that doesn't exceed N. Print that set, and the sum. So, output for that input would be:
2 8 9 12 10 4 sum:45
My issue is, I don't have something to decide between tiebreakers. The tiebreaking factor would be the set with larger amount of elements. So my program prints this:
2 43 sum:45
Here is the code (standard I/O):
int val = reader.nextInt();
int num = reader.nextInt(); // never exceeds 20
int[] cost = new int[20];
int[][] dp = new int[10000][10000];
int[][] path = new int[10000][10000];
for (int i = 0; i < num; i++) {
cost[i] = reader.nextInt();
}
for (int i = 0; i < num; i++) {
for (int j = 0; j <= val; j++) {
if (j < cost[i]) {
dp[i + 1][j] = dp[i][j];
}
else {
if (dp[i][j] < dp[i][j - cost[i]] + cost[i]) {
path[i+1][j] = 1;
dp[i + 1][j] = dp[i][j - cost[i]] + cost[i];
}
else {
dp[i + 1][j] = dp[i][j];
}
}
}
}
int k = val;
for (int i = num; i >= 1; i--) {
if (path[i][k] == 1 && k >= 0) {
System.out.print(cost[i - 1] + " ");
k = k - cost[i - 1];
}
}
System.out.print("sum:" + dp[num][val] + '\n');
You are on the right track with your T x N 2-dimensional array. But you shouldn't be tracking the accumulated cost as the value of each cell, that is already tracked by the 2nd index (j in your case). Instead, track the maximum number of elements you can sum to get to that cost so far. By doing this, you don't even need a path array.
Imagine a scenario where N = 5, T = 4, and the numbers are {4, 1, 1, 3}. The first column would track a 1 in the row j == 4 and 0 everywhere else. The second column would track a 2 in the row j == 5, a 1 in rows j == 4 and j == 1 and 0 everywhere else. You could fill it with something like this (may need some tweaking...):
dp[0][cost[0]] = 1;
for (int i = 1; i < T; i++) {
dp[i][cost[i]] = 1;
for (int j = N - 1; j >= 0; j--) {
if (j >= cost[i] && dp[i-1][j-cost[i]] > 0) {
dp[i][j] = dp[i-1][j-cost[i]] + 1;
}
dp[i][j] = Math.max(dp[i][j], dp[i-1][j]);
}
}
The dp table at the end would look like this:
Sum (j)
5 | 0 2 2 3
4 | 1 1 1 2
3 | 0 0 0 1
2 | 0 0 2 2
1 | 0 1 1 1
0 | 0 0 0 0
______________________________
cost | { 4 1 1 3 }
From this table, you know that the maximum number of elements you can use to sum to 5 is 3. To find out what those elements are, work backwards from dp[3][5]. Since dp[2][5] != dp[3][5], you must have added cost[3] (3) as your third element, so add 3 to your result set. The next value to inspect is dp[2][5 - cost[3]], or dp[2][2]. Compare that to the cell to the left, dp[1][2]. They aren't equal, so you must have added cost[2] as well (if they were equal, that means you didn't add cost[2], and the next cell to inspect would be dp[1][2]). Continue until dp[i][j] == 0 or i == 0 to construct your result set.
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int n = A.size();
// Add 1 to last digit and find carry
A.set(n - 1, A.get(n - 1) + 1);
int carry = A.get(n - 1) / 10;
A.set(n - 1, A.get(n - 1) % 10);
// Traverse from second last digit
for (int i = n - 2; i >= 0; i--) {
if (carry == 1) {
A.set(i, A.get(i) + 1);
carry = A.get(i) / 10;
A.set(i, A.get(i) % 10);
}
}
// If carry is 1, we need to add
// a 1 at the beginning of vector
if (carry == 1)
A.add(0, 1);
return A;
}
}
Question is:
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
Wrong Answer. Your program's output doesn't match the expected output. You can try testing your code with custom input and try putting debug statements in your code.
Your submission failed for the following input:
A : [ 0, 0, 4, 4, 6, 0, 9, 6, 5, 1 ]
Your function returned the following :
0 4 4 6 0 9 6 5 2
The expected returned value :
4 4 6 0 9 6 5 2
Use below method
private ArrayList<Integer> recursiveCheckZero() {
if (arrayList.get(0) == 0) {
arrayList.remove(0);
recursiveCheckZero();
} else {
return arrayList;
}
}
This method will be used to zero at first position, it would be called recursively until all zeros get removed. and when there will be no zero at first position it will return final ArrayList of integers as actual result
int sum=0;
int carry=0;
int i=0;
while (i < A.size() - 1 && A.get(i) == 0) {
A.remove(i); //remove all zeroes in front
}
for(i=A.size()-1;i>=0;i--)
{
int n=A.get(i);
sum=n+carry;
if(i==A.size()-1)
{
sum = sum+1;
}
carry=sum/10;
sum=sum%10;
A.set(i,sum);
}
if (carry !=0)
A.add(0,1);
return A;
I want to save a triangular matrix in a 1 dim array (to minimize needed space, all zeros are left out) and create a function get() to find a specific entry from the original matrix.
For example:
Lets look at the following triangular matrix :
0 1 2 3
0 0 4 5
0 0 0 6
0 0 0 0
I am saving this matrix like this:
double[] test = {1,2,3,4,5,6};
So all the zeros are left out.
I want to write a function that gives me a value of the original matrix:
get(3,4)
should give me 6
I am checking the input to see if its out of bound and if it is below or on the diagonal.
//Checking if input is valid
if (i <= n && j <= n && i >= 1 && j >= 1){
if( j <= i ){
return 0.0;
}else {
}
}
This works.
How do I proceed though? I have trouble finding the equivalent matrix entry in my array.
Any help would be appreciated.
EDIT:
My whole code:
public class dreiecksmatrix {
int n = 4;
double[] a = {1,2,3,4,5,6};
public double get( int i, int j){
//Checking if input is valid
if (i <= n && j <= n && i >= 0 && j >= 0){
if( j <= i ){
return 0.0;
}else {
}
}
return 1.0;
}
public static void main(String [] args ){
dreiecksmatrix test = new dreiecksmatrix();
System.out.println(test.get(2,3));
}
}
Here is the sample code calculating the value of top-triange. No corner cases check like i,j >= 1 yet, but it's easy to add them.
arr = [[0, 1, 2, 3, 4],
[0, 0, 5, 6, 7],
[0, 0, 0, 8, 9],
[0, 0, 0, 0, 10],
[0, 0, 0, 0, 0]];
flatArr = [1,2,3,4,5,6,7,8,9,10];
n = 5; // matrix size
i = 1;
j = 3;
if (j <= i) {
alert(0);
} else {
pos = 0;
// find an offset caused by first (i - 1) lines
for (k = 1; k < i; k++) {
pos += n - k;
}
// find an offset in line x
pos += j - i;
// array index start from 0 so decrement value
pos = pos - 1;
alert('flatArr[' + pos + '] = ' + flatArr[pos]);
}
If you were instead to store the matrix by columns, there is a simple formula for the index into test of the i,j'th matrix element.
In your example you would have
double[] test = {1,2,4,3,5,6};
If Col(i) is the index pf the start of column i
then
Col(2) = 0
Col(3) = Col(2) + 1
..
Col(n) = Col(n-1) + n-1
Hence
Col(j) = ((j-1)*(j-2))/2
The i,j matrix element is stored i further on from the start of column j,
ie at Col(j)+i, so that you should add
return test[ ((j-1)*(j-2))/2 + i];
to your code
There is an analogous formula if you must store by rows rather than columns. It's a wee bit messier. The idea is to first figure out, starting with the last non-zero row, where the ends of the rows are solved.
I have the following bit of code that I am having some difficulty with. My expectation for output should be the applicant # with their correlated test score. The first position of both arrays is for the answer key. Not quite sure where I am going wrong with this, but any help would be appreciated.
public class applicantCheck
{
//* main method
public static void main(String[] args)
{
int i = 0, j = 0, correct;
//* initialization of applicant id's and answers
int[] appID = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
char[][] appAnswers = { {'N','Y','N','N','Y','N','N','Y','N','Y'},
{'N','Y','Y','N','Y','N','Y','Y','N','Y'},
{'N','Y','N','Y','N','Y','Y','Y','N','N'},
{'N','Y','Y','N','Y','Y','Y','Y','Y','Y'},
{'Y','Y','N','N','Y','N','N','Y','Y','Y'},
{'Y','Y','N','Y','Y','Y','N','N','T','N'},
{'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'},
{'N','Y','N','N','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','N','Y','N','Y','N'},
{'Y','Y','Y','N','N','Y','Y','N','Y','N'},
{'N','N','N','N','N','N','N','N','N','N'},
{'Y','N','Y','Y','N','Y','Y','N','Y','N'},
{'N','Y','N','N','Y','Y','N','N','N','Y'},
{'N','Y','N','Y','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','Y','N','Y','N','Y'} };
System.out.println("Applicant #\t\tMark (out of " + appAnswers[i].length + ")");
for (i = 1; i < appID.length; i++)
{
System.out.printf("%-9d", appID[i]);
correct = 0;
for (j = 0; j <= i; j++)
{
if (appAnswers[0][j] == appAnswers[i][j])
{
correct++;
}
}
System.out.printf("%10d\n", correct);
} // end of for loop
System.out.println();
} // end of main
} // end of file
The output is:
--------------------Configuration: <Default>--------------------
Applicant # Mark (out of 10)
1 2
2 3
3 3
4 4
5 3
6 2
7 6
8 3
9 2
10 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at applicantCheck.main(applicantCheck.java:36)
Don't want to solve the problem for you since it is homework, but here's a hint.
Array indexes go from 0 to the number of elements -1. Check your loop to make sure it doesn't go past the end.
I haven't verified if this is the problem, but it's a red-flag:
for (j = 0; j <= i; j++)
Did you mean this?
for (j = 0; j < 10; j++)
You only have 10 in each row. But i goes up to 14 or so. Therefore j will go out of bounds.
Instead of
for (j = 0; j <= i; j++)
try
for (j = 0; j < 10; j++)
since the array is always the same length.