having issues with arrays sum and return. Algorithm is also having issues with a single value array. Idea is to sum up numbers and form a new array until there's only one value left. For example Array [1,2,3,2] turns into [3,5,5], [8,10] and finally [18]. What is the best way to sum up array values and return it?
public class Arraytest {
int count(int[] t) {
if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
System.out.println(tt[i]);
}
count(tt);
}
return 0;
}
}
public class Main {
public static void main(String[] args) {
Arraytest at = new Arraytest();
System.out.println(t.count(new int[] {1,2,3,4,5})); // 48
System.out.println(t.count(new int[] {2})); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})); // 2538
}}
static int count(int[] t) {
if(t.length == 1)
return t[0];
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++)
tt[i] += t[i] + t[i + 1];
return count(tt);
}
return 0;
}
At the end you always returned zero instead of returning the last int in the array
Working Code:
public class Main {
public static void main(String[] args) {
Main t = new Main();
System.out.println(t.count(new int[] {1,2,3,4,5})[0]); // 48
System.out.println(t.count(new int[] {2})[0]); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})[0]); // 323
}
static int[] count(int[] t) {
if(t.length == 1)
return t;
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
}
return count(tt);
}
return null;
}
}
Related
I'm trying to solve https://leetcode.com/problems/longest-repeating-substring/
I want to use rolling hash to match strings.
However, my codes don't seem to work when I deal with modulo.
For a string with all same characters, the maximum length of repeating substring should be string.length - 1.
public class Main {
public static void main(String[] args) {
String str = "bbbbbbbbbbbbbbbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
}
class Solution {
public int longestRepeatingSubstring(String S) {
HashSet<Long> h = new HashSet();
long mod = (long)1e7 + 7;
for(int i = S.length() - 1; i >0; i--){
h = new HashSet();
long c = 0;
int j = 0;
for(; j < i; j ++){
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
}
h.add(c);
for(; j < S.length(); j++){
c -= (S.charAt(j - i ) - 'a') * Math.pow(26,i-1)% mod;
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
if(h.contains(c)){
return i;
}
h.add(c);
}
}
return 0;
}
}
Playground for my codes: https://leetcode.com/playground/F4HkxbFQ
We cannot see your original link, we need a password.
The usage of modulo seems to be really complex.
Why not try something like this
class Scratch {
// "static void main" must be defined in a public class.
public static void main(String[] args) {
String str = "bbaaabbbbccbbbbbbzzzbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
static class Solution {
public int longestRepeatingSubstring(String s) {
int max = -1;
int currentLength = 1;
char[] array = s.toCharArray();
for (int index = 1; index < array.length; index++) {
if (array[index - 1] == array[index]) {
currentLength++;
max = Math.max(max, currentLength);
} else {
currentLength = 1;
}
}
return max;
}
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
Trying to save odd numbers between 2 numbers in an array
public class OddNumber {
static int[] oddNumbers(int l, int r) {
if (r <= l)
return null;
int size = ((r - l) / 2) + 1;
int arr[] = new int[size];
int p = 0;
for (int i = l; i <= r; i++) {
if (i % 2 != 0) {
arr[p] = i;
p++;
}
}
return arr;
}
public static void main(String[] args) {
System.out.println("Odd numbers between 2 & 9 are: " + oddNumbers(2, 9));
}
}
It is always giving same junk value "Odd numbers between 2 & 9 are: [I#15db9742". I dont know what is the problem
public class Solution {
static int[] oddNumbers(int l, int r) {
List<Integer> list = new ArrayList<>();
for (int i = l; i <= r; i++) {
if (i % 2 == 0) {
list.add(i);
}
}
int arr[] = new int[list.size()];
for(int i = 0 ; i < list.size(); i++) {
arr[i]=list.get(i);
}
return arr;
}
public static void main(String[] args) {
int arr[] = oddNumbers(2, 9);
for(int i : arr) {
System.out.print(i + " ");
}
}
}
After many times to try to solve this issue, I can't seem to solve my dilemma. When trying to run my program, the unsorted array will not sort when printing "Sorted Array". Is there something that I'm doing wrong?
public class RecursiveSorter {
private int[] sortedArray;
private int[] array;
public RecursiveSorter() {
array = new int[1];
}
public RecursiveSorter(int[] a) {
array = a;
}
public void setArray(int[] a) {
array = a;
}
public int[] getSortedArray() {
return sortedArray;
}
public int[] getOriginalArray() {
return array;
}
public int[] sort() {
sortedArray = array;
recursiveSort(sortedArray.length - 1);
return sortedArray;
}
public int[] recursiveSort(int endIndex) {
if (endIndex > 0) {
int m = getMaxIndex(endIndex, sortedArray);
swap(m, endIndex, sortedArray);
recursiveSort(endIndex-1);
}
return sortedArray;
}
public int getMaxIndex(int endIndex, int[] a) {
int max = a[0];
int maxIndex = 0;
for (int i = 1; i < endIndex; i++) {
if (a[i] < max) {
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
//Changed it to make sure that it is swapping the elements correctly
public void swap(int src, int dest, int[] a) {
if(dest <= src)
{
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
dest++;
src++;
}
}
public String toString() {
return "Original: " + prettyPrint(getOriginalArray()) + "\n" +
"Sorted: " + prettyPrint(getSortedArray());
}
private String prettyPrint(int[] a) {
String s = "";
for (int i : a)
s += i + " ";
return s;
}
public static void main(String[] args) {
// Automate running, but not testing
int[] array = {5, 67, 12, 20};
RecursiveSorter s = new RecursiveSorter(array);
s.sort();
System.out.println(s); // uses Sorter.toString
}
}
You have 3 problems. 2 are in getMaxIndex(): you were not including the last element in the test for the max, and the test for max is not the right. You are computing the min.
public int getMaxIndex(int endIndex, int[] a) {
int max = a[0];
int maxIndex = 0;
for (int i = 1; i <= endIndex; i++) { // use <= instead of <
if (a[i] > max) { // change < in >
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
And one problem in swap()
public void swap(int src, int dest, int[] a) {
if(src <= dest) // reverse src and dest
{
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
dest++; // no use, dest is local
src++; // idem
}
}
Then you will have:
Original: 5 12 20 67
Sorted: 5 12 20 67
Actually the orginal array is modified because array and sortedArray reference the same array of int. There is no copy in Java. When you do
public int[] sort() {
sortedArray = array;
recursiveSort(sortedArray.length - 1);
return sortedArray;
}
sortedArray points to the same int[] as array. If you want to keep the orginal one, you need to explicitly do a copy, for instance with System.arrayCopy(...).
I traced the problem down to two points:
first, you have an unnecessary if in swap(...):
public void swap(int src, int dest, int[] a)
{
// if(dest <= src)
// {
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
// dest++;
// src++;
// }
}
Second, you have a little bug in the for loop of getMaxIndex(...):
public int getMaxIndex(int endIndex, int[] a)
{
int max = a[0];
int maxIndex = 0;
for (int i = 1; i <= endIndex; i++) // substituted < with <=
{
if (a[i] < max)
{
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
With these changes (and mentionded System.arraycopy), the algorithm should work as intended.
Why you are not sing
// sorting array in #java.util.Arrays;
Arrays.sort(array);
And dont need to recusive call and all
If you need to write your own code, then Choose any sorting algorthim, implement that one by your own.
private static void sort(int[] array){
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
Here's my implementation of Merge Sort in java
import java.io.*;
import java.util.Arrays;
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while(k < D.length){ D[k++] = C[j++]; }
}
if(j == C.length)
{
//Copy the remainder of B into D
while(k < D.length){ D[k++] = B[i++]; }
}
if(i<B.length && j<C.length)
{
if(B[i] > C[j]){ D[k++] = B[i++]; }
else { D[k++] = C[j++]; }
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
The output I get is
2 1
From what I can tell there seems a problem with my division of the right sub array.
What am I doing wrong?
Here is the javadoc of copyOfRange:
Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)
I highlighted two words you should pay special attention to ;-)
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
With your code [1,3,5,2,4] is split into [1,3] and [2,4]. Good luck
This piece of code works: you had couple of errors:
see next diffs:
rightSubArray method
copy the remainder of B
copy the remainder of C
The code that works follows:
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2,
Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while (j < C.length) {
D[k++] = C[j++];
}
}
if(j == C.length)
{
//Copy the remainder of B into D
while (i < B.length) {
D[k++] = B[i++];
}
}
if (i < B.length && j < C.length)
{
if (B[i] > C[j]) {
D[k++] = B[i++];
} else {
D[k++] = C[j++];
}
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
I found a rigth solution in Robert Sedgewick book "Algorithms on java language"
Read here about merge
So I am trying to make the following code into a recursive method, insertion sort, but for as much as I try I cannot. Can anyone help me?
public static void insertionSort(int[] array){
for (int i = 1; i < array.length; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
EDIT:
I was thinking of something like this, but it doesn't look very recursive to me...
public static void insertionSort(int[] array, int index){
if(index < array.length){
int j = index;
int B = array[index];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
insertionSort(array, index + 1);
}
}
Try this:
public class RecursiveInsertionSort {
static int[] arr = {5, 2, 4, 6, 1, 3};
int maxIndex = arr.length;
public static void main(String[] args) {
print(arr);
new RecursiveInsertionSort().sort(arr.length);
}
/*
The sorting function uses 'index' instead of 'copying the array' in each
recursive call to conserve memory and improve efficiency.
*/
private int sort(int maxIndex) {
if (maxIndex <= 1) {
// at this point maxIndex points to the second element in the array.
return maxIndex;
}
maxIndex = sort(maxIndex - 1); // recursive call
// save a copy of the value in variable 'key'.
// This value will be placed in the correct position
// after the while loop below ends.
int key = arr[maxIndex];
int i = maxIndex - 1;
// compare value in 'key' with all the elements in array
// that come before the element key.
while ((i >= 0) && (arr[i] > key)) {
arr[i+1] = arr[i];
i--;
}
arr[i+1] = key;
print(arr);
return maxIndex + 1;
}
// code to print the array on the console.
private static void print(int[] arr) {
System.out.println();
for (int i : arr) {
System.out.print(i + ", ");
}
}
}
public static void insertionSort(int[] array, int index) {
if(array.length == index + 1) return;
insertionSort(array, index + 1);
// insert array[index] into the array
}
You can try this code. It works correctly.
public static int[] InsertionSort(int[] dizi, int n)
{
int i;
if (n < 1) {
InsertionSort(dizi, n - 1);
}
else {
int key = dizi[n];
i = n - 1;
while (i >= 0 && dizi[i] > key) {
dizi[i + 1] = dizi[i];
i = i - 1;
}
dizi[i + 1] = key;
}
return dizi;
}
for the recursion algorithm, we start with the whole array A[1..n], we sort A[1..n-1] and then insert A[n] into the correct position.
public int[] insertionSort(int[] array)
{
//base case
if(array.length==1) return new int[]{ array[0] };
//get array[0..n-1] and sort it
int[] arrayToSort = new int[array.length - 1]{ };
System.arraycopy(array, 0, arrayToSort, 0, array.length -1);
int[] B = insertionSort(arrayToSort);
//now, insert array[n] into its correct position
int[] C = merge(B, array[array.length - 1]);
return C;
}
private int[] merge(int[] array, int n)
{
int[] arrayToReturn = new int[array.length + 1] {};
int j = array.length-1;
while(j>=0 && n <= array[j])
{
arrayToReturn[j+1]=array[j;
j--;
}
arrayToReturn[j] =
}
Try below code by providing ele as an integer array, sortedIndex=index of first element and index=index of second element:
public static void insertionSort(int[] ele, int sortedIndex, int index) {
if (sortedIndex < ele.length) {
if (index < ele.length) {
if (ele[sortedIndex] > ele[index]) {
ele[sortedIndex] += ele[index];
ele[index] = ele[sortedIndex] - ele[index];
ele[sortedIndex] = ele[sortedIndex] - ele[index];
}
insertionSort(ele, sortedIndex, index + 1);
return;
}
if (index == ele.length) {
sortedIndex++;
}
insertionSort(ele, sortedIndex, sortedIndex + 1);
}
}
public static void sort(int[] A, int p, int r) {
if (p < r) {
int q = r - 1;
sort(A, p, q);
combine(A, p, q, r);
}
}
private static void combine(int[] A, int p, int q, int r) {
int i = q - p;
int val = A[r];
while (i >= 0 && val < A[p + i]) {
A[p + i + 1] = A[p + i];
A[p + i] = val;
i--;
}
}
public static void main(String... strings) {
int[] A = { 2, 5, 3, 1, 7 };
sort(A, 0, A.length - 1);
Arrays.stream(A).sequential().forEach(i -> System.out.print(i + ", "));
}
public class test
{
public static void main(String[] args){
test h = new test();
int a[] = { 5, 8, 9, 13, 65, 74, 25, 44, 67, 2, 1 };
h.ins_rec(a, a.length-1);
for(int i=0; i<a.length; i++)
log(a[i]);
}
void ins_rec(int a[], int j){
if( j == 0 ) return;
ins_rec(a, j - 1);
int key = a[ j ];
sort(a, key, j - 1);
}
void sort(int a[], int key, int i){
if( (i < 0) || (a[i] < key) ) {
a[ i + 1 ] = key;
return;
}
a[ i + 1 ] = a[ i ];
sort(a, key, i - 1);
}
private static void log(int aMessage){
System.out.println("\t\t"+aMessage);
}
}