Moving array elements left and right - java

So as part of the Vector class I'm trying to create, I also want the ability for the user to be able to shift the elements in the array an 'n' number of places depending on what is specified. If the user inputs a number that is larger than the array size, then the elements continue shifting back to the start and moving. An example would be:
1 2 3 4 (shifted 1) => 4 1 2 3
1 2 3 4 (shifted 4) => 1 2 3 4
1 2 3 4 (shifted 5) => 4 1 2 3
I don't have much code so far except:
public Vector shifted(int amount) {
Vector vectorShifted = new Vector(length);
for (int i = 0; i < length; i++);
vectorShifted.elements[i] = this.elements[i + amount]
}
return vectorShifted;
}
However, when I run this program and a number greater than length is entered, an error is displayed. Is there a way of modifying this code in that any number, positive or negative can be inputted and shift the values across?

Just like lazary2 said, you can use the modulo operator %
Change:
vectorShifted.elements[i] = this.elements[i + amount]
to vectorShifted.elements[i] = this.elements[(i + amount) % length]
If you want to use Array:
Integer[] array = {0,1,2,3,4};
Collections.rotate(Arrays.asList(array), 3);
System.out.println(Arrays.toString(array)); //[2, 3, 4, 0, 1]

Related

Path with maximum average value

import java.util.Scanner;
public class maxAvgPath {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] c = new int[n+1][n+1];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
c[i][j]=sc.nextInt();
}
}
float sum = c[0][0];
float m = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (c[i][j + 1] < c[i + 1][j]) {
sum = sum + c[i + 1][j];
m++;
} else {
sum = sum + c[i][j + 1];
m++;
}
}
}
System.out.println((sum/m));
}
}
Given a square matrix of size N*N, where each cell is associated with a specific cost. A path is defined as a specific sequence of cells which starts from the top-left cell move only right or down and ends on bottom right cell. We want to find a path with the maximum average over all existing paths. Average is computed as total cost divided by the number of cells visited in the path.
Input : Matrix = [1, 2, 3,
4, 5, 6,
7, 8, 9]
Output : 5.8
Path with maximum average is, 1 -> 4 -> 7 -> 8 -> 9
Sum of the path is 29 and average is 29/5 = 5.8
But I am not getting the correct output can some tell where is my mistake?
Your m should always be 2 * n - 1. Regardless of the chosen path, you will always move either right or down, starting from top-left corner. You have n - 1 rows and n - 1 columns, so you're moving right exactly n - 1 and moving down exactly n - 1 times. In total, counting the top-left, you have 1 + (n - 1) + (n - 1) numbers on your ideal path. Therefore, you're not looking for a max average, you're actually looking for a maximum sum.
Your loops are not exactly in sync with what you're trying to do. Let's say, for the given matrix, when i = 0, j is 0, that you discover that 4 is bigger than 2. You pick the 4, m[1][0], and then you should check the max of m[1][1] and m[2][0] ... but your loop moves to ... i = 0, j = 1, allowing you to check m[1][2] and m[1][1].
You're also using a Greedy aproach which won't always give you the best result, e.g. [1 2 9, 3 4 9, 5 2 9], your algorithm will pick 1, move down to 3 and 5 then right to 2 and 9, giving you a total of 20. However, the ideal path is 1, right to 2 and 9, then down to 9 and 9, for a grand total of 30.
One approach to solve this is to keep the loops, but instead of maintaining one sum, you need to keep track of multiple sums and picking a max at every step.
e.g. for [1 2 9, 3 4 9, 5 2 9], you initialize your sum matrix with 0 and start navigating.
For sum[0][0], there is only one possible sum, which is picking up m[0][0]. This continues for the entire 1st row, so your sum matrix is now [1 3 12, 0 0 0, 0 0 0]. For sum[1][0], there is also only one possible sum, moving down from m[0][0], so sum[1][0] is m[0][0] + m[1][0]. And here the fun starts.
For sum[1][1], you need to pick between sum[0][1] and sum[1][0] and add m[1][1]. You will of course pick sum[1][0] (which is really m[0][0] + m[1][0]) and add m[1][1] to it, so sum[1][1] is 8. Therefore, if your maximal path ever travels to r1c1, you know that you've picked the maximum possible sum so far.
I will also highlight the next step, sum[1][2], where you have to pick between sum[0][2] and sum[1][1] and add m[1][2]. We know sum[0][2] is 12, sum[1][1] is 8, so, if our path ever reaches cell r1c2, we know that we need to pick first row entirely and then move down instead(m[0][0], m[0][1], m[0][2], m[1][2]) of moving down and picking the next row (m[0][0], m[1][0], m[1][1], m[1][2]), so your current maximal sum in sum[1][2] is 21 and your sum matrix is [1 3 12, 4 8 21, 0 0 0].
Final row is the same thing:
sum[2][0] = sum[1][0] + m[2][0]
sum[2][1] = max(sum[1][1], sum[2][0]) + m[2][1]
sum[2][2] = max(sum[1][2], sum[2][1]) + m[2][2]
Your sum matrix eventually becomes [ 1 3 12, 4 8 21, 9 11 30 ], therefore your
max is 30. You have picked up 2 * 3 - 1 = 5 numbers, so your average is 6.
Illustrating the sum matrix is also interesting:
1 3 12
4 8 21
9 11 30
If you ever want to determine what was the path you've chosen from top-left to bottom-right, you just need to follow the sums, in descending order(keeping in mind the move-right or move-down rule), 30 -> 21 -> 12 -> 3 -> 1.
I will leave the coding part as an exercise, you have all the details you need.
(sorry for bad formatting and long text)

What is the Time and Space Complexity of LeetCode 241. Different Ways to Add Parentheses?

I am trying to understand what is time complexity of leetcode 241. Different ways to add parentheses. I have used memoization technique. My friend was asked in Google coding round, he couldn't give correct time and space complexity. I found same problem in Leetcode.
Problem:
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1:
Input: "2-1-1"
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: "2 * 3 - 4 * 5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(4*5))) = -34
((23)-(45)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Code:
import java.util.*;
class Solution {
Map<String, List<Integer>> map = new HashMap<>();
public List<Integer> diffWaysToCompute(String input) {
if(map.containsKey(input)) {
return map.get(input);
}
List<Integer> result = new ArrayList<>();
int length = input.length();
for(int i = 0; i< length; i++) {
char character = input.charAt(i);
if(isOperator(character)) {
String part1 = input.substring(0, i);
String part2 = input.substring(i + 1);
List<Integer> part1Result = diffWaysToCompute(part1);
List<Integer> part2Result = diffWaysToCompute(part2);
computeAndStoreResult(input, result, i, part1Result, part2Result);
}
}
//store in map...
map.put(input, result);
//this is when only one input is present.
// input 3 ==> nothing is added in result so add 3 ...
if(result.size() == 0) {
result.add(Integer.valueOf(input));
}
return result;
}
private boolean isOperator(char character) {
return character == '-' || character == '*' || character == '+';
}
private void computeAndStoreResult(String input, List<Integer> result, int i, List<Integer> part1Result, List<Integer> part2Result) {
for(Integer p1 : part1Result) {
for(Integer p2 : part2Result) {
int c= 0;
switch (input.charAt(i)) {
case '+':
c = p1+p2;
break;
case '-':
c = p1-p2;
break;
case '*':
c = p1*p2;
break;
}
result.add(c);
}
}
}
}
I have research on many sites could not find good explanation
This is how recursive tree looks like: Techinque used is divide and conquer with memoization.
Some useful links that I found.
https://www.cnblogs.com/yrbbest/p/5006196.html
https://just4once.gitbooks.io/leetcode-notes/content/leetcode/divide-and-conquer/241-different-ways-to-add-parentheses.html
Observation
If an expression consists of a single number, then there's 1 way to place parentheses.
If there's only 1 math operator in an expression, then there's only 1 way to place parentheses to obtain a relevant result. For example, for 3 + 4 it's (3 + 4).
If there are 2 math operators in an expression, then there are 2 ways to place parentheses. For example, for 3 + 4 - 2, the method will split the expression by + into 3 and 4 - 2, and then by - into 3 + 4 and 2. So, it's 2 ways.
If there are 3 math operators in an expression, then it's 5 results. For example, 1 + 2 - 3 * 4 can be split into 1 and 2 - 3 * 4, 1 + 2 and 3 * 4, 1 + 2 - 3 and 4. As we've learned from 2) and 3), the number of ways is 2 + 1 + 2 = 5` ways.
If there are 4 math operators in an expression, then it's 14 results. For example, 1 + 2 - 3 * 4 + 5 can be split into 1 and 2 - 3 * 4 + 5, 1 + 2 and 3 * 4 + 5, 1 + 2 - 3 and 4 + 5, 1 + 2 - 3 * 4 and 5. As we've learned from 2), 3) and 4) the number of ways is 5 + 2 + 2 + 5 = 14 ways correspondingly.
If the sequence is continued then it will be 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, .... As you can see, it grows exponentially.
Such sequence of numbers has a name and is called Catalan numbers.
Application for your algorithm
As you may have already realised, your algorithm will become exponential even after you obtain results for your left and right subexpressions split by the first math operator.
So, if there are 10 math operators, then after computing the results for the first configuration (expression is split by the first math operator) their number will be 4862.
So, not only is your time complexity exponential, but also your space complexity since you save all the results in a list.

Addition in field with finite int elements?

I need to write a function (in Java) which has the following input:
int amountFieldElements
int summandOne
int summandTwo
amountFieldElement describes the amount of int numbers in a range starting from 1 (e.g. 1, 2, 3, 4 or just 1). summandOne is a int from this range, summandTwo can be any non-negative int.
The function has to add summandTwo to summandOne. If the result is bigger then amountFieldElement, it has to start over from 1.
I tried to simply use modulo: (summandOne + summandTwo) % amountFieldElements
But this is often wrong, e.g. (3 + 1) % 4 = 0 but I'd need it to be 4.
Example: If amountFieldElements = 4:
2 + 2 = 4 would stay as 4
3 + 2 = 5 would become 1
4 + 2 = 6 would become 2 etc
or for amountFieldElements = 1
1 + 0 = 1 would stay as 1
1 + 1 = 2 would also be 1
-> any result would be 1 here
something like this will work:
int result = (summandOne + summandTwo) % amountFieldElements;
if (result == 0) result = amountFieldElements;
another method, shorter but harder to understand is:
int result = (summandOne + summandTwo - 1) % amountFieldElements + 1;

Generating series

I'm looking for an explanation on the following problem
Given an input - array of integers such as 1 2 3 4 I want to produce all of the possible "permutations" which look like this0 0 0 1 , 0 0 0 2, first one goes like this until 0 0 0 4 , next one looks like this 0 0 1 0 and then 0 0 1 1 .I hope you got my point.I have already constructed an iterative algorithm which produces the series but it uses too much memory for an input of size 10, the solution I'm looking for doesn't use recursion. Please note that there are (n + 1)! (0,0,0,0 included) possiblities.
The input is limited to integers and it is always the case that the count of values generated equals the count of the input values.
EDIT
Please note that there might be such a solution here in Stackoverflow but I can't really define a proper name for the problem that's why if anyone has any clue on how to actually name this problem,please do share!
Thanks!
To generate your series you basically do this:
Start with an array containing only zeroes, of the correct length
Iterate, and for each iteration do "basic math" like incrementation of the number, as though each element of the array is a single digit of a larger number.
Basically increment the last number by 1
If this ends up being higher than the max for that position, reset it to 0 and move on to the digit to the left
If it didn't end up being higher than the max, you got a new solution
When the move-on-to-the-digit-to-the-left operation falls off the left end of the array, you're done
Here is a LINQPad solution that demonstrates:
void Main()
{
CountedPermutations(1, 2, 3)
.Select(l => new { a = l[0], b = l[1], c = l[2] })
.Dump();
}
public static IEnumerable<int[]> CountedPermutations(params int[] maxValues)
{
int[] results = new int[maxValues.Length];
yield return results; // the all-zeroes solution
while (true)
{
// Increment to next solution
if (CountedPermutationsMutate(results, maxValues))
{
// make a copy of the array and yield return it
// we make copies so that if the outside code puts everything in a
// collection, we don't just end up with N references to the same array
// with the same values.
yield return results.ToArray();
}
else
break;
}
}
public static bool CountedPermutationsMutate(int[] values, int[] maxValues)
{
int index = values.Length - 1;
bool gotSolution;
while (true)
{
if (values[index] < maxValues[index])
{
// won't overflow this position, so we got a new solution
values[index]++;
gotSolution = true;
break;
}
else
{
// Overflow in this position, reset to 0
// and move on to the next digit to the left
values[index] = 0;
index--;
// If we fell off the left end of the array, we're done
if (index < 0)
{
gotSolution = false;
break;
}
}
}
return gotSolution;
}
This will output:
0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3
Consider using iterators to avoid storing of every generated value.

Algorithm to partition a list into groups

I have a list of names.
I want to partition this list into groups of a specified size. All groups should be equal to or less than the specified size, with an equal as possible group size across the groups, and as close to the specified size as possible.
What algorithm (Java-esque pseudo code if possible please!) determines the most appropriate group sizes?
For example:
List contains 13 names - max team size 3.
Output (group sizes): 3, 3, 3, 2, 2
List contains 13 names - max team size 4.
Output: 4, 3, 3, 3
List contains 31 names - max team size 5.
Output: 5, 5, 5, 4, 4, 4, 4
List contains 31 names - max team size 6.
Output: 6, 5, 5, 5, 5, 5
List contains 31 names - max team size 10.
Output: 8, 8, 8, 7
It's pretty straightforward. You calculate the result of N div M and add 1 to have the correct number of arrays (N is the list length and M the max team size), then you iterate on all arrays to add an item until you run out of items
example : 43 names, max team number 4 => 43 mod 4 + 1 = 11, remains 3. so 11 arrays (10 with 4 and 1 with 3)
I'm not going to write code for this, but
If the list size is a multiple of the max team size, divide by team size to get the number of groups, all of max size, and stop.
Integer-divide the list size by the max team size, then add one. That's the number of groups.
Subtract the list size from that next higher multiple; that's the number of teams that are one less than the max size.
This obviously only works for inputs that are close to working out; it fails if the max team size is large compared to the size of the list.
If the number of items in the list is N and the max number of items in sublist is K, the solution of your problem comes from solving a Linear Diophantine Equation
K*x + (K-1)*y = N
with additional constraints
x > 0
y >= 0
Where x is the number of sublists of the exact size K, and y is the number of sublists of length K-1.
EDIT : Because of the coefficients to the equation are always off by one from each other, the solution is rather straightforward:
int m = (N+K-1)/K;
int x = N - (K-1)*m; // Number of "full" lists
int y = K*M - N; // Number of off-by-one lists
Example 1:
N = 31, K = 5
m = (31+5-1)/5 = 7
x = 31 - (5-1)*7 = 3 // 3 lists of 5 items
y = 5*7 - 31 = 4 // 4 lists of 4 items
Example 2:
N = 32, K = 4
m = (32+4-1)/4 = 8
x = 32 - (4-1)*8 = 8 // 8 lists of 4 items
y = 4*8 - 32 = 0 // no lists of 3 items
Look up an algorithm for solving linear Diophantine equations on the net - it is not that complicated, if you understand Euclidean algorithm well. The number of solutions of the equation without constraints is infinite, but once you add the constraints, you should get a single solution.
public class Q {
public static void q(int size, int maxTeamSize) {
int numOfTeams = size / maxTeamSize;
int mod = size % maxTeamSize;
numOfTeams += (mod > 0) ? 1 : 0;
System.out.print("\n(" + size + ":" + maxTeamSize + ")");
for (int i = 0; i < numOfTeams; i++) {
System.out.print(" " + (size / numOfTeams + ((i < mod) ? 1 : 0)));
}
}
public static void main(String[] args) {
q(13, 3);
q(12, 4);
q(31, 5);
q(31, 6);
}
}

Categories