So I have a Shifter program that only allows positive integers.
Question: how do I make it so It also receives negative numbers. I.e
Program ask for number of shifts, I enter 3 and it outputs
3 2 1 15 14 13 12 11 10 9 8 7 6 5 4
public static void shiftRight(int[] list)
{
if (list.length < 2) return;
int last = list[list.length - 1];
for(int i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
if this is to shift right. How would I make it so It will shift depending on the number I input? i.e. Right for positive and Left for negative.
I would implement a shiftLeft(int[]) method according your method, and then decide which use
int input;
int[] array;
//fill the input, array etc.
if(input<0){
for(int i=0;i<-input;i++){
shiftLeft(array);
}
}else{
for(int i=0;i<input;i++){
shiftRight(array);
}
}
btw, this shifting is not very efficient way.
You could use the following function. It uses a temporary array to store the rotated/shifted array and then copies back to the original array. The arrays that is original array and temporary array are traversed twice, so it will be efficient instead for calling a shift function on the array many times.
/**
* This function performs the right/left shift operations
* on the array of integers.
*
* #param int[] array array of integers
* #param int shift Amount of right or
* left shift. If shift
* is grater than zero,
* function performs
* right shift, otherwise
* the function perform
* left shift.
*/
public static void shift_array (int[] array, int shift) {
/*
* If array is null, then return
* from the function.
*/
if (array == null) {
return;
}
boolean is_left_shift = (shift < 0); // store whether
// left shift is
// intended.
int shift_amount; // store the amount of shift
int array_length = array.length; // length of the
// array
if (shift < 0) {
shift_amount = shift * -1; // if shift is less than zero
// then shift_amount is set as
// product of shift and -1.
} else {
shift_amount = shift;
}
/*
* Make sure the shift_amount is within the
* length of the array.
*/
shift_amount = shift_amount % array_length;
/*
* If the shift_amount is zero, we
* have nothing to do. Return.
*/
if (shift_amount == 0) {
return;
}
/*
* Create a temp array and copy the
* elements in the array at appropriate
* positions.
*/
if (!is_left_shift) {
/*
* Temp array to store elements at shifted
* positions.
*/
int[] temp = new int[array_length];
/*
* Iterate throught the array
*/
for (int i = 0; i < array_length; ++i) {
int temp_index;
/*
* Map the elements to appropriate
* positions in the temp array.
*/
if ((i + shift_amount) < array_length) {
temp_index = i + shift_amount;
} else {
temp_index = (i + shift_amount) % array_length;;
}
/*
* Copy the array element into the temp array.
*/
temp[temp_index] = array[i];
}
/*
* Copy back from temp array to array
*/
for (int i = 0; i < array_length; ++i) {
array[i] = temp[i];
}
} else {
/*
* Temp array to store elements at shifted
* positions.
*/
int[] temp = new int[array_length];
/*
* Iterate throught the array
*/
for (int i = 0; i < array_length; ++i) {
int temp_index;
/*
* Map the elements to appropriate
* positions in the temp array.
*/
if ((i - shift_amount) >= 0) {
temp_index = i - shift_amount;
} else {
temp_index = i - shift_amount + array_length;
}
/*
* Copy the array element into the temp array.
*/
temp[temp_index] = array[i];
}
/*
* Copy back from temp array to array
*/
for (int i = 0; i < array_length; ++i) {
array[i] = temp[i];
}
}
}
Related
For a Java class we have to make a Dynamic array. Cannot use arraylist.
Here is where I define the class
public class DynamicArray {
private int array[];
private int size;
Here is the called constructor:
/**
* DynamicArray copies the array
* #param obj
*/
public DynamicArray(DynamicArray obj) {
array = obj.toArray();
size = obj.getSize();
}
Under the main method, here is where I create the new array object and try to sort and shuffle (as well as a few of the other methods, but those are working):
/**
* Calling the copy constructor, which calls the toArray method
* Calling get method
* Calling indexOfMethod
* Calling findMax
* Calling findMin
* Calling shuffle
*/
DynamicArray array3 = new DynamicArray(array2);
array3.push(100);
array3.push(150);
array3.push(100);
System.out.println(array3);
array3.pop();
System.out.println(array3);
System.out.println("This number is at index 5: " + array3.get(5));
System.out.println("The number 100 first appears at index: " + array3.indexOf(100));
System.out.println("The highest number is: " + array3.findMax());
System.out.println("The lowest number is: " + array3.findMin());
System.out.println(array3);
array3.shuffle();
System.out.println(array3);
array3.sort(array3.toArray());
The toArray method is this:
/**
* toArray accessor returns the array
* #return
*/
public int[] toArray() {
int arrayCopy[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
arrayCopy[i] = array[i];
}
return arrayCopy;
}
And the sort and shuffle methods are this:
/**
* isEmpty returns size = 0 is array is empty
* #return 0 if empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* sort sorts the numbers in the array
*/
public void sort(int [] array) {
int lastPos;
int index;
int newNum;
for (lastPos = array.length - 1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if (array[index] > array[index + 1]) {
newNum = array[index];
array[index] = array[index + 1];
array[index + 1] = newNum;
}
}
}
}
/**
* shuffle shuffles the array
*/
public void shuffle() {
Random r = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = r.nextInt(i);
int tmp = array[i];
array[i] = array[index];
array[index] = tmp;
}
}
The output for sort has 0's in it:
0, 0, 0, 10, 0, 0, 150, 0, 2,
And shuffle is not changing anything.
These were created with help in the tutoring lab and I've compared them to recommendations online.
What's going on?
Updated:
Here's the array2:
/**
* Calling constructor with parameter
* also calling push to add items to the array
*/
DynamicArray array2 = new DynamicArray(5);
array2.push(4);
array2.push(10);
array2.push(15);
array2.push(18);
array2.push(2);
array2.push(25);
System.out.println("Size is: " + array2.getSize());
array2.push(20);
System.out.println("Size is: " + array2.getSize());
System.out.println(array2);
Here's getSize()
/**
* getSize gets size of the array
* #return size
*/
public int getSize() {
return size;
}
Could you please provide information how array2 is instantinated? It is starting point for the algorithm.
getSize() implementation would be useful also.
For now you can check sorting algorithms here:
https://www.geeksforgeeks.org/sorting-algorithms/
e.g. Bubble sort is quite easy to understand and implement.
For shuffling implementation you can check:
http://www.vogella.com/tutorials/JavaAlgorithmsShuffle/article.html
I'm working on a school assignment and the assignment was to make a heap sorting (In Place) program. Now the program works perfectly fine for arrays with under +- 20 elements, above that it occasionally messes up, however I can't seem to find what's wrong.
/**
* swaps two elements in an array
*
* #param a array
* #param i position of element to swap in a
* #param j position of element to swap in a
*/
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
/**
* restores the heap property in a heap represented as an array
* 4 5 0
* <p>
* restoreHeap([4, 5, 0], 0, 3)
* biggest = 1
*
* #param heap array representation of a heap,
* which might be invalidated
* #param root index of the root of the heap,
* which might be a subtree of the overall heap
* #param range index of the last element in the heap,
* array elements with an index > range are not part of the heap
* <p>
* when the heap property is invalid at root,
* the method fixes the heap first locally before fixing the affected subtree
*/
public static void restoreHeap(int[] heap, int root, int range) {
final int left = root * 2 + 1;
final int right = root * 2 + 2;
final int size = root + range;
int biggest = root;
if (left < size && heap[left] > heap[biggest]) {
biggest = left;
}
if (right < size && heap[right] > heap[biggest]) {
biggest = right;
}
if (biggest != root) {
swap(heap, biggest, root);
restoreHeap(heap, biggest, range - (biggest - root));
}
}
/**
* turns an array of integers into a heap
* <p>
* this is an in-place algorithm, the heap is built in the array itself
* 1 2 4 5 9 3
*
* #param array of integer numbers,
* on return, this array represents a valid heap
*/
public static void buildHeap(int[] array) {
for (int i = 1; i < array.length; i++) {
int temp = i;
while (array[temp / 2] < array[temp]) {
swap(array, temp / 2, temp);
temp /= 2;
}
}
}
/**
* sorts an array of integer numbers
* <p>
* this is an in-place algorithm, the heap is built in the array itself
*
* #param array of elements, on return, this array represents a valid heap
*/
public static void inPlaceHeapSort(int[] array) {
buildHeap(array);
int arrSize = array.length;
while (arrSize > 1) {
swap(array, arrSize - 1, 0);
arrSize--;
restoreHeap(array, 0, arrSize);
}
}
The skeleton for the methods was already there so if you're asking why certain parameters are even there, it's because it was compulsory.
The problem seem's to be indexing, the indexing for left and right seems to be wrong
final int left = root * 2 + 1;
final int right = root * 2 + 2;
here you should change the code to
final int left = root * 2;
final int right = root * 2 + 1;
Also remember that you have to index the array from 1, instead of 0.
This question already has answers here:
Getting permutations of an int[] removing duplicates sets
(5 answers)
Closed 7 years ago.
I want to generate all distinct permutations of array of integers. The array may contain duplicates. but i want to generate all distinct permutations. I have tried next permutation and recursive methods which tend to be very slow. Please suggest.
There are n! different permutations of n elements. Generating a single permutation is cost n (strictly) so the minimum cost of any permutation generation algorithm would be O(n*n!)
Steinhaus–Johnson–Trotter algorithm is one of those algorithms. There are improvements like Shimon Even's and other algorithms like Heap's but none get them under O(n*n!)
Googling "permutation algorithm" gets several different algorithms you can implement, although most use recursion and that means another stack step. Steinhaus–Johnson–Trotter is defined as iterative, so shouldn't get that problem.
Here's a Java implementation
import java.util.Arrays;
import java.util.Iterator;
/**
* this implementation is based in Steinhaus–Johnson–Trotter algorithm and
* Shimon Even's improvement;
*
* #see https
* ://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm
*
*/
public class Permutations implements Iterator<int[]> {
/**
* direction[i] = -1 if the element i has to move to the left, +1 to the
* right, 0 if it does not need to move
*/
private int[] direction;
/**
* inversePermutation[i] is the position of element i in permutation; It's
* called inverse permutation because if p2 is the inverse permutation of
* p1, then p1 is the inverse permutation of p2
*/
private int[] inversePermutation;
/**
* current permutation
*/
private int[] permutation;
/**
* #param numElements
* >= 1
*/
public Permutations(int numElements) {
// initial permutation
permutation = new int[numElements];
for (int i = 0; i < numElements; i++) {
permutation[i] = i;
}
// the support elements
inversePermutation = Arrays.copyOf(permutation, numElements);
direction = new int[numElements];
Arrays.fill(direction, -1);
direction[0] = 0;
}
/**
* Swaps the elements in array at positions i1 and i2
*
* #param array
* #param i1
* #param i2
*/
private static void swap(int[] array, int i1, int i2) {
int temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
}
/**
* prepares permutation to be the next one to return
*/
private void buildNextPermutation() {
// find the largest element with a nonzero direction, and swaps it in
// the indicated direction
int index = -1;
for (int i = 0; i < direction.length; i++) {
if (direction[permutation[i]] != 0
&& (index < 0 || permutation[index] < permutation[i])) {
index = i;
}
}
if (index < 0) {
// there are no more permutations
permutation = null;
} else {
// element we're moving
int chosenElement = permutation[index];
// direction we're moving
int dir = direction[chosenElement];
// index2 is the new position of chosenElement
int index2 = index + dir;
// we'll swap positions elements permutation[index] and
// permutation[index2] in permutation, to keep inversePermutation we
// have to swap inversePermutation's elements at index
// permutation[index] and permutation[index2]
swap(inversePermutation, permutation[index], permutation[index2]);
swap(permutation, index, index2);
// update directions
if (index2 == 0 || index2 == permutation.length - 1
|| permutation[index2 + dir] > permutation[index2]) {
// direction of chosen element
direction[chosenElement] = 0;
}
// all elements greater that chosenElement set its direction to +1
// if they're before index-1 or -1 if they're after
for (int i = chosenElement + 1; i < direction.length; i++) {
if (inversePermutation[i] > index2) {
direction[i] = -1;
} else {
direction[i] = 1;
}
}
}
}
#Override
public boolean hasNext() {
return permutation != null;
}
#Override
public int[] next() {
int[] result = Arrays.copyOf(permutation, permutation.length);
buildNextPermutation();
return result;
}
}
Hi I am working with a voice command project. So I want to receive user's voice at first then I want to check the matches and then I want to do something according to the command. For this, I found a way to match the strings using org.apache.commons.lang3.StringUtils but I find so many trouble with this. For ex:- I face problem when I go to import the apache's external library to my android studio.
So my question is that:- is there any other way to compare the user's voice data and my specific command without using Apache's StringUtils method? Please help if you can
Take the source right from the library (Obviously follow the requirements of the Apache license)
https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html
Line 6865
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from http://www.merriampark.com/ld.htm</p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from http://www.merriampark.com/ldjava.htm</p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","") = 0
* StringUtils.getLevenshteinDistance("","a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* #param s the first String, must not be null
* #param t the second String, must not be null
* #return result distance
* #throws IllegalArgumentException if either String input {#code null}
* #since 3.0 Changed signature from getLevenshteinDistance(String, String) to
* getLevenshteinDistance(CharSequence, CharSequence)
*/
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
The difference between this impl. and the previous is that, rather
than creating and retaining a matrix of size s.length() + 1 by t.length() + 1,
we maintain two single-dimensional arrays of length s.length() + 1. The first, d,
is the 'current working' distance array that maintains the newest distance cost
counts as we iterate through the characters of String s. Each time we increment
the index of String t we are comparing, d is copied to p, the second int[]. Doing so
allows us to retain the previous cost counts as required by the algorithm (taking
the minimum of the cost count to the left, up one, and diagonally up and to the left
of the current cost count being calculated). (Note that the arrays aren't really
copied anymore, just switched...this is clearly much better than cloning an array
or doing a System.arraycopy() each time through the outer loop.)
Effectively, the difference between the two implementations is this one does not
cause an out of memory condition when calculating the LD over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
There are many string functions you can use to compare strings, for example
if (result.equals("hello")) {
doSomething();
}
compares two strings
result.startsWith("search for") {
doSomething()
}
checks the beginning of the result
result.matches("yes|sure") {
doSomething()
}
checks result with regular expression.
You can find all that in a Java textbook. See for example
https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html
If you want to use Levenshtein distance you can insert the following function in your code:
public int LevenshteinDistance (String s0, String s1) {
int len0 = s0.length() + 1;
int len1 = s1.length() + 1;
// the array of distances
int[] cost = new int[len0];
int[] newcost = new int[len0];
// initial cost of skipping prefix in String s0
for (int i = 0; i < len0; i++) cost[i] = i;
// dynamically computing the array of distances
// transformation cost for each letter in s1
for (int j = 1; j < len1; j++) {
// initial cost of skipping prefix in String s1
newcost[0] = j;
// transformation cost for each letter in s0
for(int i = 1; i < len0; i++) {
// matching current letters in both strings
int match = (s0.charAt(i - 1) == s1.charAt(j - 1)) ? 0 : 1;
// computing cost for each transformation
int cost_replace = cost[i - 1] + match;
int cost_insert = cost[i] + 1;
int cost_delete = newcost[i - 1] + 1;
// keep minimum cost
newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace);
}
// swap cost/newcost arrays
int[] swap = cost; cost = newcost; newcost = swap;
}
// the distance is the cost for transforming all letters in both strings
return cost[len0 - 1];
}
I have tested that my partitioning algorithm works well, but when it comes time in the implementation to make use of it, I get an array that is not sorted. Since this is for a class, there's a certain I need to write the class itself so that I can return the answer as string. My problem is most likely in the qkSort() method. Here's the code:
private static int splitterElement;
public static void main (String[] args){
System.out.println(myMethod());
}
public static String myMethod() {
String result = "";
int[] testArray = null;
testArray = populateArray(testArray, 7, 10);
result += "Before sort: \n" + printArray(testArray);
testArray = qkSort(testArray,1,testArray.length);
result += "After sort: \n" + printArray(testArray);
return result;
}
//Method to continually call the partition() method
public static int[] qkSort(int[] x, int left, int right){
if (right - left >= 1) {
//after running this method, the global variable splitterElement is assigned.
x = partition(x,left,right);
qkSort(x,left,splitterElement-1);
qkSort(x,splitterElement + 1,right);
}
//base case. if right-left = 0, then the array length is 1,
//and that is already sorted
return x;
}
/**
* Populates an integer array with random integers. Should be used only with
* non-itialized integer arrays.
*
* #param x an uninitialized array of integers and will be returned once it is populated.
* #param sizeOfArray The size that array x will be initialized to.
* #param rangeOfValues The range of values that that each element can be. This value should
* not surpass the maximum value for integers, but no error-checking is performed.
* #return
*/
public static int[] populateArray (int[] x, int sizeOfArray, int rangeOfValues){
x = new int[sizeOfArray];
for (int i = 0; i < sizeOfArray; i++){
x[i] = (int)(Math.random() * rangeOfValues); //place a random number from 0 to rangeOfValues into array.
}
return x;
}
/**
*
* #param x An integer array. It is assumed that x is initialized when the method is called.
* #param left
* #param right The length of the array can be used for the right int.
* #see #populateArray(int[], int, int)
* #return
*/
public static int[] partition (int[] x, int left, int right){
//element of the splitter
int l = (int) (Math.random() * x.length);
splitterElement = l;
x = swap (x,left,l);
//value of the splitter
int t = x[left];
int i = left;
for (int j = left + 1; j < right; j++){
if (x[j] < t){
i++;
x = swap (x,i,j);
}
}
x = swap(x,left,i);
return x;
}
/**
* Places the value at index1 in index2, and places the value at index2 in index1.
*
* #param array The array that will be worked on.
* #param index1 The first place we will switch values.
* #param index2 The second place we will switch values.
* #return
*/
public static int[] swap (int[] array, int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
}
/**
* A simple print method that prints an array.
* #param array Input.
*/
public static String printArray (int[] array){
String result = "";
for (int i = 0; i < array.length; i++){
result += array[i] + " ";
}
result += "\n";
return result;
}
}
Output:
Before sort:
8 9 7 3 4 2 6
After sort:
8 6 3 9 7 2 4
Thanks for any ideas on what my problem is!
I see several issues in your code:
1) the methods don't need to return the array, you could find a better use for the return value
2) using a global variable splitterElement doesn't work because its value can change during the first recursive call to qkSort. Method partition could return its value instead of returning the array, which is useless.
3) the first line of the partition method:
int l = (int) (Math.random() * x.length);
should be:
int l = left + (int) (Math.random() * (right - left));
because youre partitionning the range between left and right, not the whole array.