The code below has stylistic flaws plus a bug or two. List as many flaws as you can.
public int palindromeCount (int start, int finish) {
int k = start;
int returnVal = 0;
while (k<finish) {
int temp = k;
int r = 0;
while (temp > 0) {
r = 10 * r + temp%10;
temp = temp/10;
}
if (r == k) {
returnVal++;
}
k++;
}
return returnVal;
}
Palindrome is basically a number that has the same value if reversed, such as 11. The code here needs to browse through a range and finally end up with the amount of palindromes within that range. I'm doing this to learn loops.
Here is my progress:
public class Counter{
public Counter(){
}
public int palindromeCount (int start, int finish) {
int returnVal = 0;
int temp = start;
while (start < finish) {
int reverse = 0;
while (temp != 0) {
reverse = 10 * reverse + temp % 10;
temp = temp/10;
}
if (temp == start) {
returnVal = returnVal + 1;
}
start = start + 1;
}
return returnVal;
}
}
I think you posted this before, as far as I've tested it, it works well.
public static int palindromeCount(int start, int finish) {
int k = start;
int returnVal = 0;
while (k <= finish) { // Changed to <= to consider "finish" too
int temp = k;
int r = 0;
while (temp > 0) {
r = 10 * r + temp % 10;
temp = temp / 10;
}
if (r == k) {
returnVal++;
}
k++;
}
return returnVal;
}
Related
I going to do searching the value in the array, did I need to create a method to handle it? For example, the array logged 32,21,13,44,22, and I going to find 22 of the comparison. How can I implement this?
public class binarySearch {
public static void main(String [] args) {
int i = binarySearch(0, new int[]{32,21,13,44,22});
System.out.println("Iterations: " + i);
}
public static int binarySearch(int key, int[] array) {
int left = 0;
int mid;
int right = array.length - 1;
int i = 0;
while (left <= right) {
mid = (left + right) / 2;
int comp = Integer.compare(key, array[mid]);
i++;
if (comp < 0) {
right = mid - 1;
} else if (comp > 0) {
left = mid + 1;
} else {
break; // success
}
}
return i;
}
}
My final answer is here. May help you all in the future.
public static int binarySearch(int key, int[] array) {
int left = 0;
int mid;
int right = array.length - 1;
int i = 0;
while (left <= right) {
mid = (left + right) / 2;
int comp = Integer.compare(key, array[mid]);
i++;
if (comp < 0) {
right = mid - 1;
} else if (comp > 0) {
left = mid + 1;
} else {
break; // success
}
}
return i;
}
If you have shuffled array, all you can do is go through an array and find your number.
BinarySearch works only with sorted array. I think your solution could look like this:
public static int binarySearch(int[] arr, int key) {
Arrays.sort(arr);
return Arrays.binarySearch(arr, key);
}
You have been given a binary string containing only the characters '1' and '0'.
Calculate how many characters of the string need to be changed in order to make the binary string such that each of its substrings of at least a certain length contains at least one "1" character.
I came to think of the following idea but it fails for many testcases:
public static int minimumMoves(String s, int d) {
int n = s.length();
int i=0, answer = 0;
while(i<n)
{
boolean hasOne = false;
int j=i;
while(j<n && j<i+d)
{
if(s.charAt(j) == '1')
{
hasOne = true;
break;
}
j++;
}
if(!hasOne) {
answer++;
i += d;
}
else i++;
}
return answer;
}
Also my algorithm runs on O(|s|2) time. Can anyone suggest ideas on O(|s|) time?
Just throwing off an idea:
return s.split("(?<=\\G.{" + String.valueof(d) + "})").stream().filter(str -> str.contains("1")).count()
You just need to break ensure there is no run of d zeros.
public static int minimumMoves(String s, int d) {
int result = 0;
int runLength = 0;
for(char c: s.toCharArray()) {
if (c == '0') {
runLength += 1;
if (runLength == d) { // we need to break this run
result += 1;
runLength = 0;
}
} else {
runLength = 0;
}
}
return result;
}
I used the sliding window technique and Deque to solve this. This is my accepted solution:
public static int minimumMoves(String s, int d) {
int n = s.length();
Deque<Character> dq = new LinkedList<>();
int count = 0, answer = 0;
for(int i=0; i<d; i++)
{
if(s.charAt(i) == '1') count++;
dq.addLast(s.charAt(i));
}
if(count == 0) {
answer++;
count++;
dq.removeLast();
dq.addLast('1');
}
int i=d;
while(i<n)
{
if(dq.getFirst() == '1') count--;
dq.removeFirst();
if(s.charAt(i) == '1') count++;
dq.addLast(s.charAt(i));
if(count == 0)
{
answer++;
dq.removeLast();
dq.addLast('1');
count++;
}
i++;
}
return answer;
}
You just need to use a sliding window and a count of 1s so far at each index. Use a sliding window of d and if you don't see any ones so far, update the last index of that window with 1 and increment the result.
Code below:
public static int minimumMoves(String s, int d) {
int n = s.length();
int[] count = new int[n+1];
int res = 0;
for ( int i = 1; i <= d; i++ ) {
if ( s.charAt(i-1) == '1') count[i] = count[i-1]+1;
else count[i] = count[i-1];
}
if ( count[d] == 0 ) {
res++;
count[d] = 1;
}
for ( int i = d+1; i <= n; i++ ) {
if ( s.charAt(i-1) == '0' ) {
count[i] = count[i-1];
int ones = count[i] - count[i-d];
if ( ones == 0 ) {
count[i] = count[i-1] + 1;
res++;
}
} else {
count[i] = count[i-1] + 1;
}
}
return res;
}
Thought of another implementation you can do for this by working from the maximum possible changes (assumes at start that all values are '0' in String), reduce it when it finds a '1' value, and then jump to the next substring start. This allows it to run in O(n) and Ω(n/m) (n = String length, m = Substring length).
public static int minimumMoves(String s, int d)
{
char[] a = s.toCharArray();
//Total possible changes (not counting tail)
if(a.length < d)
return 0;
int t = (int) a.length / d;
//Total possible changes (counting tail)
//int t = (int) Math.ceil((double) a.length / (double) d);
for(int i = 0; i < a.length; i++)
{
if(a[i] == '1')
{
t--;
//Calculate index for start of next substring
i = (i / d + 1) * d - 1;
}
}
return t;
}
I am working on a homework task where I am supposed to make a function that will do a binary insertion sort, but my function does not seem to work properly.
Here I have tried to combine a binary search function with a insertion sort function (it is specified in the homework task that it needs to be in the form of a function: insertionSort(int[] array, int lo, int hi))
public static void insertionSort(int[] array, int lo, int hi){
int mid;
int pos;
for (int i = 1; i < array.length; i++) {
int x= array[i];
while (lo < hi) {
mid = lo + (hi -lo)/2;
if (x == array[mid]) {
pos = mid;
}
if (x > array[mid]) {
lo = mid+1;
}
else if (x < array[mid]) {
hi = mid-1;
}
}
pos = lo;
for (int j = i; j > pos; j--) {
array[j] = array[j-1];
}
array[pos] = x;
}
}
If I try to run it with the list {2,5,1,8,3}, the output will be
2 5 1 3 1 (if lo < hi and if lo > hi)
2 5 3 8 5 (if lo==hi)
What I am expecting though, is a sorted list...
Any idea of what I am doing wrong?
Just to give you a possible idea:
public static void insertionSort(int[] array) {
if (array.length <= 1) {
return;
}
// Start with an initially sorted part.
int loSorted = array.length - 1;
//int hiSorted = array.length;
while (loSorted > 0) {
// Take one from the array
int x = array[0];
// Where in the sorted part to insert?
int insertI = insertPosition(array, loSorted);
// Insert x at insertI
...
--loSorted;
}
}
whenever I need binary search, my function looks the following way:
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
In your main method the call looks like:
public static void main(String[] args) {
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
I hope I was able to help you!
Thank you for your input. I changed the function a little bit, and it seems to be working now
` public static void insertionSort(int[] array, int lo, int hi){
int mid;
int pos;
for (int i = 1; i < array.length; i++) {
int j = i -1;
int x = array[i];
while (lo <= hi) {
mid = lo + (hi -lo)/2;
if (x == array[mid]) {
pos = mid;
break;
}
if (x > array[mid]) {
lo = mid+1;
}
else if (x < array[mid]) {
hi = mid-1;
}
}
while (j >= 0 && array[j] > x) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
the problem seemed to lay in the last part, where I was trying to move the elements into their right positions. The function is probably not perfect tho, so constructive criticism is welcome :)
With the Introduction to algorithm .The Professor intro that the random quick sort can decrease the percentage of bad situation and improve the performance of time cost.But I wonder if there any problem with my code that cause the result
in contrast.
Here are my java code
public class quickSort {
public final int size = 200000;
public final int times = 10;
#Test
public void quick_sort() {
int test1[] = new int[size];
int test2[];
int k = 0;
long t1 = 0;
long t2 = 0;
for (int i = 0; i < size; i++) {
test1[i] = i;
}
test2 = test1.clone();
while (k < times) {
shuffle(test1);
shuffle(test2);
long start1 = System.currentTimeMillis();
split1(test1, 0, test1.length -1);
t1 += System.currentTimeMillis() - start1;
long start2 = System.currentTimeMillis();
split2(test2, 0, test2.length -1);
t2 += System.currentTimeMillis() - start2;
k++;
}
System.out.println("normal quick sort time is" + t1 + "ms");
System.out.println("random quick sort time is " + t2 + "ms");
}
public void split1(int[] arr, int start, int end) {
if (start >= end) {
return;
} else {
int middle = sort(arr, start, end);
split1(arr, start, middle - 1);
split1(arr, middle + 1, end);
}
}
public void split2(int[] arr, int start, int end) {
if (start >= end) {
return;
} else {
int middle = random_sort(arr, start, end);
split2(arr, start, middle - 1);
split2(arr, middle + 1, end);
}
}
// random quick sort
public int random_sort(int[] arr, int start, int end) {
int random = start + new Random().nextInt(end - start + 1);
int key = arr[random];
int loop = start;
int front = random == start ? start + 1 : start;
while (loop <= end) {
if (loop == random) {
loop++;
continue;
}
if (arr[loop] < key) {
int temp = arr[loop];
arr[loop] = arr[front];
arr[front] = temp;
front = front + 1 == random ? front += 2 : front + 1;
}
loop++;
}
if (front < end) {
int temp = arr[random];
arr[random] = arr[front];
arr[front] = temp;
} else {
front = end;
}
return front;
}
// normal quick sort
public int sort(int[] arr, int start, int end) {
int loop = start;
int key = arr[start];
int front = start + 1;
while (loop <= end) {
if (key > arr[loop]) {
int temp = arr[loop];
arr[loop] = arr[front];
arr[front++] = temp;
}
loop++;
}
if (front != 1) {
int temp = arr[front - 1];
arr[front - 1] = arr[start];
arr[start] = temp;
}
return front - 1;
}
// shuffle the Array
public void shuffle(int[] arr) {
int length = arr.length;
int random_num = 0;
for (int i = 0; i < length; i++) {
random_num = new Random().nextInt(length);
int temp = arr[i];
arr[i] = arr[random_num];
arr[random_num] = temp;
}
}
}
I am writing two recursive java programs, however they both have errors. The largest method has an out of bounds error on the final return. The second code says max is an incompatible type.
I am fairly new at Java and the codes probably look a little messy so any tips on how to make it easier or nicer are welcome!
this program finds the largest digit in the array:
public static int largest(int data[], int n) {
if (n == 0) {
}
return largest(data, 0, n-1); //line107
}
public static int largest(int array[], int LF, int RT){
if (LF == RT){ //1 element array
}
else {
// int large = largest(array, LF++, size - 1);
// return x =
int largeLF = array[LF];
int largeRT = array[RT];
int mid = ((RT - LF) / 2) + LF;
if (LF < mid - 1){
if (array[LF] > largeLF){
largeLF = array[LF];
}
largest(array, LF + 1, RT); //line 125
}
else if (RT > mid - 1){
if (array[RT] > largeRT){
largeRT = array[RT];
}
largest(array, LF, RT - 1); //line 131
}
else {
if (array[mid] > largeLF){
largeLF = array[mid];
}
}
if (largeRT > largeLF){
LF = largeRT;
}
LF = largeLF;
}
return array[LF]; //line 144
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at ArrayUtilities.largest(ArrayUtilities.java:144)
at ArrayUtilities.largest(ArrayUtilities.java:131)
at ArrayUtilities.largest(ArrayUtilities.java:131)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:107)
at ArrayUtilitiesTest.main(ArrayUtilitiesTest.java:5)
this code finds the block of numbers with the greatest sum
public static int maxBlock(int data[], int n) {
if (n == 0) {
}
else {
maxBlock(data, n-1);
}
return n;
}
public static void maxBlock(int data[], int LF, int RT) {
int n = RT;
for (LF = 0; LF < n; LF++){
for (RT = LF; RT < n; RT++){
int sum = 0;
for (int i = LF; i <= RT; i++){
sum += data[i];
}
int max = data[0];
for (LF = 0; LF < n; LF++){
sum = 0;
for (RT = LF; RT < n; RT++){
sum += data[RT];
if (sum > max){
max = sum;
}
System.out.println(max);
}
}
return max;
}
}
}
I am still confused on the returns since they are not global variables, how do you transfer the values?
Any help would be great, Thanks!