Add one in a number of arraylist - java

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;

Related

Get Immediate Successor in a Given Number Sequence

In an infinite sequence of numbers [2, 5, 7, 22, 25, 27, 52, 55, 57, 72, 75, 77, 222, ...].
Given any number in this sequence get the immediate successor number.
Example:
Input Output
22 25
77 222
5 7
I have written the below logic to find the next number in a sequence.
public static int getNextNumInSequence(Integer sequenceCurrentNum) {
List<Integer> sequence = new ArrayList<>();
sequence.add(2);
sequence.add(5);
sequence.add(7);
if(sequence.get(0).equals(sequenceCurrentNum))
return sequence.get(1);
else if(sequence.get(1).equals(sequenceCurrentNum))
return sequence.get(2);
//This is not a finite loop, just for my testing i am running 300 iterations.
for(int i=0;i<300;i++) {
if(sequence.get(i).equals(sequenceCurrentNum)) {
return sequence.get(i+1);
}
int nextVal = sequence.get(i)*10;
Integer firstSeq = nextVal + sequence.get(0);
Integer secondSeq = nextVal + sequence.get(1);
Integer thirdSeq = nextVal + sequence.get(2);
sequence.add(firstSeq);
sequence.add(secondSeq);
sequence.add(thirdSeq);
if(firstSeq.equals(sequenceCurrentNum)) {
return secondSeq;
}else if(secondSeq.equals(sequenceCurrentNum)) {
return thirdSeq;
}
}
return 0;
}
My Approach:
I am constructing the entire sequence from the beginning
Then checking if we have reached to the given number in sequence.
Then return the successor.
Drawbacks:
I am constructing the entire sequence to reach to given number.
Memory wise and performance wise not suggestable.
Please help to understand, is there any better approach to get the successor without constructing entire sequence.
Example: Given 277755 should return 277757. (Without constructing the
entire sequnce)
Note: The sequence will not be provided as an input to our function. The only input we will be given is a valid number from the sequence.
Try this.
public static int getNextNumInSequence(Integer sequenceCurrentNum) {
int head = sequenceCurrentNum / 10;
int tail = sequenceCurrentNum % 10;
int headNext = head == 0 ? 2 : getNextNumInSequence(head);
if (headNext == 0) return 0;
switch (tail) {
case 2: return head * 10 + 5;
case 5: return head * 10 + 7;
case 7: return headNext * 10 + 2;
default: return 0;
}
}
public static void main(String[] args) {
for (int i = 0, k = 2; i < 20; ++i, k = getNextNumInSequence(k))
System.out.println(i + " : " + k);
}
output:
0 : 2
1 : 5
2 : 7
3 : 22
4 : 25
5 : 27
6 : 52
7 : 55
8 : 57
9 : 72
10 : 75
11 : 77
12 : 222
13 : 225
14 : 227
15 : 252
16 : 255
17 : 257
18 : 272
19 : 275
You can also get n-th number.
public static int getNumAtIndex(int n) {
int h = n / 3;
int t = n % 3;
return (h == 0 ? 0 : getNumAtIndex(h) * 10)
+ (t == 0 ? 2 : t == 1 ? 5 : 7);
}
test:
public static void main(String[] args) {
for (int i = 0; i < 10; ++i)
System.out.println(i + " : " + getNumAtIndex(i));
}
output:
0 : 2
1 : 5
2 : 7
3 : 52
4 : 55
5 : 57
6 : 72
7 : 75
8 : 77
9 : 522
First try to understand what is the logic behind the sequence. If you look carefully to the numbers, you may see counting in ternary base. To be more clear, let's replace '2' by '0', '5' by '1' and '7' by '2'. Then your sequence becomes:
(0, 1, 2, 10, 11, 12, 20, 21, 22, 100, 101, 102, ...)
It's just counting.
So the thing is to get the next number in ternary base, but using the digits 2, 5, 7. We must take care of digit 7: if we increment it, we get 2 but we have a carry for the digit before.
Here is a sample code:
public static Integer getNextNumInSequence(Integer number)
{
int digits[] = {2,5,7};
int idx_digits[] = {-1, -1, 0, -1, -1, 1, -1, 2, -1, -1};
Integer next_number = 0;
int carry = 1;
Integer pow10 = 1;
while (number>0)
{
int digit = number%10; //extract last digit
int idx_d = idx_digits[digit]; //get index of digit -- must be 0,1 or 2
if (idx_d==-1)
{
System.out.println("Invalid number");
return -1;
}
next_number += digits[(idx_d+carry)%3]*pow10; //compute next digit in sequence, taking care of the carry
carry = (digit==7)?1:0; //carry is 1 only if the current digit is 7
pow10 *= 10; //increment
number /= 10; //erase last digit
if (carry==0) //if no carry, we can stop the loop here, it's not useful to continue
{
break;
}
}
// at this point, either number>0 or carry==1
return ((carry>0)?2:number)*pow10+next_number; //final number is the digit sequence [2 if carry else number ; next_number]
}
You can solve this recursively.
If the final digit of the given number is 2 or 5, then it is easy: just change that final digit to 5 or 7 respectively.
Otherwise (when the final digit is 7), solve the problem without the last digit, and then append the digit 2 to that result. Of course, "without last digit" means an integer division by 10, and "appending" means multiplying by 10 and then adding the value of the digit.
Here is the function:
public static int getNextNumInSequence(Integer curr) {
if (curr % 10 == 2) return curr + 3;
if (curr % 10 == 5) return curr + 2;
if (curr == 7) return 22;
return getNextNumInSequence(curr / 10) * 10 + 2;
}
Note that one call has worst case time complexity of O(logn) where n is the value of the function argument, but amortised time complexity is O(1) per call.
To construct the list, you can simply do this:
List<Integer> list = Arrays.asList(2, 5, 7, 22, 25, 27, 52, 55, 57, 72, 75, 77, 222);
Note that there are cases where there is not successor. Here I will return null in those cases:
public static Integer getNextNumInSequence(List<Integer> list, Integer num) {
int pos = list.indexOf(num);
if (pos >= 0 && pos+1 < list.size()) {
return list.get(pos+1);
}
return null;
}
Note that I've added a parameter list so that you don't have to build the list each time you want to do a search.
In your example, the list is sorted; If it's always the case, you can use a binary search: Collections.binarySearch(list, num) instead of list.indexOf(num).
OK. If I understand correctly, you have three initial values:
static final int[] initial = {2, 5, 7};
and you can calculate the value at position ix like this:
private static int calculate(int ix) {
int div = ix/initial.length;
int rest = ix%initial.length;
int value = 0;
if (div > 0) {
value = 10*calculate(div-1);
}
return value+initial[rest];
}
To get the successor of num:
public static Integer getNextNumInSequence(int num) {
for (int i = 0; ; ++i) {
int cur = calculate(i);
if (cur == num) {
return calculate(i+1);
} else if (cur > num) {
return null;
}
}
}

Java recursion issue

Consider the following serie:
1, 1, 2, 2, 4, 8, 32, 256, ...
I wrote this method in Java:
public static int Fibmul(int n){
if (n == 1) return 1;
else if (n == 0) return 0;
else if (n < 0) return -1; // -1 means 'nil'
else {
n = Fibmul(n - 2) * Fibmul(n - 1);
}
return n;
}
To calculate the serie just multiply the last two positions of the elements to obtain the next element, E.g Fibmul(4) should return 4 and Fibmul(6) should return 32.
But this code is wrong an I don't have more ideas, I have clear the algorithm over the paper but I don't know how to implement it.
Can anybody help me?
Thanks in advance.
You're not going to get any higher numbers if your starting numbers are 0 and/or 1.
If your starting numbers are 1 and 2, you will get something like the sequence you described.
public static int Fibmul(int n){
if (n == 1) return 2;
else if (n == 0) return 1;
else if (n < 0) return -1; // -1 means 'nil'
else {
n = Fibmul(n - 2) * Fibmul(n - 1);
}
return n;
}
This will give
1, 2, 2, 4, 8, 32, ...
It cannot start with 1,1,2 if you want to follow the rule you stated, because 1*1 does not equal 2.
NB: Your sequence is actually the ordinary Fibonacci series but with each term used as a power of 2.
Fibonacci: 0, 1, 1, 2, 3, 5, 13, ...
Fibmul: 2**0, 2**1, 2**1, 2**2, 2**3, 2**5, 2**13, ...
You simply need an extra solution for when n == 2 because otherwise you'll remain stuck with 1, 1, 1, 1, 1, ...
public static int Fibmul(int n) {
if (n == 2)
return 2;
if (n == 1)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return -1; // -1 means 'nil'
return Fibmul(n - 2) * Fibmul(n - 1);
}
Testing it works as expected
Fibmul(0) = 0
Fibmul(1) = 1
Fibmul(2) = 2
Fibmul(3) = 2
Fibmul(4) = 4
Fibmul(5) = 8
Fibmul(6) = 32
Fibmul(7) = 256
Fibmul(8) = 8192
Fibmul(9) = 2097152
I think you are missing the 2 value. This should return 2, and the rest is fine:
else if (n == 2) return 2;
See here: https://code.sololearn.com/ca22A0a236a2

Triangular matrix get() in one dimensional array

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.

ArrayList Removing first element

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

selection sort method for array

i have this method that i got from a website about selection sort that i need to check how it works :
import java.util.Arrays;
public class SelectionSort {
public static void selectionSort(int[] data, int low, int high) {
if (low < high) {
swap(data, low, findMinIndex(data, low));
selectionSort(data, low + 1, high);
}
}
public static void swap(int[] array, int index1, int index2) {
int tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
public static int findMinIndex(int[] data, int index) {
int minIndex;
if (index == data.length - 1)
return index;
minIndex = findMinIndex(data, index + 1);
if (data[minIndex] < data[index])
return minIndex;
else
return index;
}
public static void main (String[] args) {
int[] numbers = {3, 15, 1, 9, 6, 12, 21, 17, 8};
SelectionSort.selectionSort(numbers, 0, numbers.length);
System.out.println(Arrays.toString(numbers));
}
}
can you help me undrestand why is that int high get the last index of the array ?how?
In this specific code...
findMinIndex compares the element in a given index to all elements in front of it (elements with higher indices) up to the very last element of the array.
So if you have an array:
int[] a = { 7, 4, 2, 6 };
and you call findMinIndex(a, 0); it will first check to see that there is an element after index 0. That's what this part does index == data.length - 1. If there is no element after, it will simply return the index it was passed. But there obviously is an element after index 0 since the array has length 4.
Now that we've confirmed that there are elements after our index, it is time to get the index of the smallest element after index. This way we can compare the element at our index to all the elements in front of it to see which element is smallest in the range index to array.length - 1 (inclusive). This is accomplished through recursion:
minIndex = findMinIndex(data, index + 1);
So the next few calls will go like this:
findMinIndex(data, 1);
// is there an element after 1? There is. So we end up calling findMinIndex again...
findMinIndex(data, 2); // is there an element after 2? Yes. Recurse...
findMinIndex(data, 3); // is there an element after 3? No. That's the end of the array
// remember this part? it's used now to finally terminate the recursion
if (index == data.length - 1)
return index; // this equals 3
Now the recursive calls begin to unwind.
// index == 2 because the 2nd to last index is 2. remember our array has length 4 and indices 0-3.
minIndex = 3; // this is the index of the last element
if (data[3] < data[2]) { // look at our array 'a', is 6 less than 2?
return 3; // No it is not. so this is not returned
} else {
return 2; // we end up return the index (2) of the smaller element (2)
}
It unwinds again.
// index == 1
minIndex = 2; // we compared 2 and 3 and found that the element at index 2 was smaller
if (data[2] < data[1]) { // is 2 less than 4?
return 2; // yes, this is returned because the element at index 2 is less than the element at index 1
} else {
return 1; // false!
}
And one more time.
// index == 0 this is our original call! when we said findMinIndex(a, 0);
minIndex = 2;
if (data[2] < data[0]) { // is 2 less than 7?
return 2; // yes it is
} else {
return 0; // false!
}
Finally, the method will return 2. This is because of all the elements after (inclusive) index 0, the element with index 2 is the smallest.
Now let's look at selectionSort. When you first call it, you need to use this format:
selectionSort(a, 0, 4); // where 4 is the length of the array
This function also uses recursion. The swap method is self explanatory (it swaps the elements at 2 different indices). Now let's go through the recursive calls:
if (0 < 4) { // True of course
swap(a, 0, findMinIndex(a, 0));
selectionSort(data, 0 + 1, 4);
}
Remember that we found the smallest element after 0 (inclusive) had an index of 2. So the above code can be replaced with:
if (0 < 4) { // True of course
swap(a, 0, 2);
selectionSort(data, 0 + 1, 4);
}
This will change our array to {2, 4, 7, 6} because we swapped the elements at index 0 and index 2. Notice how index 0 is now the smallest element in the array with a value of 2.
Now selectionSort is called again to make sure the array is in order from least to greatest. The next call will look like this:
// low == 1 and high == 4
if (1 < 4) { // true
swap(a, 1, findMinIndex(data, 1));
selectionSort(a, 1 + 1, 4);
}
Remember our array is now {2, 4, 7, 6}. That means that the smallest element after index 1 (value of 4) is actually just 4. So the above code would be equal to:
// low == 1 and high == 4
if (1 < 4) { // true
swap(a, 1, 1);
selectionSort(a, 1 + 1, 4);
}
The swap does nothing in this case. Now the method is called recursively again.
// low == 2 and high == 4
if (2 < 4) { // true
swap(a, 2, findMinIndex(data, 2));
selectionSort(a, 2 + 1, 4);
}
Our array wasn't changed with the last swap. The smallest element after index 2 (inclusive) will be 6, which has an index of 3. That means our code above is equal to:
// low == 2 and high == 4
if (2 < 4) { // true
swap(a, 2, 3);
selectionSort(a, 2 + 1, 4);
}
Now our array becomes { 2, 4, 6, 7 }. Hooray it's in order from least to greatest! But that's not where it ends. There is another recursion call just to make sure that it's really in order.
// low == 3 and high == 4
if (3 < 4) { // true
swap(a, 3, findMinIndex(data, 3));
selectionSort(a, 3 + 1, 4);
}
Remember in findMinIndex it checks to see if there are any elements after the given index? There are no elements after index 3, so it will just return 3. That means the above code is equal to:
// low == 3 and high == 4
if (3 < 4) { // true
swap(a, 3, 3);
selectionSort(a, 3 + 1, 4);
}
This swap does nothing. And as you can see, there is still another recursion call! This will be the final one.
// low == 4 and high == 4
if (4 < 4) { // false, 4 is not less than 4
swap(a, 4, findMinIndex(a, 4)); // none of this happens
selectionSort(a, 4 + 1, 4); // no recursion
}
// finally returns void
The end.
It's a lot easier to understand selection sorts with loops as opposed to recursion.
It is the size of the array, it is used to know when is over.
Every cycle:
First: checks if any element with and index higher than low (low starts at 0) is lower and if that is the case swaps them.
Second: increase low
It stops when low is not lower than high (size of the array).
See the definition of selection sort:
http://en.wikipedia.org/wiki/Selection_sort
For anyone looking for another way to do selection sort using recursion, here is one way to do it.
//the method that will be called to sort the array recursively
public static void selectionSort(double[] arr) {
selectionSort(arr, 0);
}
//this is a recursive helper method.
//arr is the array to be sorted and index is the current index in
//the array which will be swapped with the smallest value in the
//remaining part of the array
private static void selectionSort(double[] arr, int index) {
//if index has reached the second to last value, there are
//no more values to be swapped
if (index < arr.length - 1) {
//let index, at first, be the index at which the smallest element is located
int smallestIndex = index;
//find the smallest entry in the array from i=index to i=index.length - 1
for (int i = index + 1; i < arr.length; i++) {
//if the element at i is smaller than the element at smallestIndex, then update the value of smallestIndex
if (arr[i] < arr[smallestIndex]) {
smallestIndex = i;
}
}
//swap the elements of arr[smallestIndex] and arr[index]
double t = arr[index];
arr[index] = arr[smallestIndex];
arr[smallestIndex] = t;
selectionSort(arr, index + 1);
}
}

Categories