I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}
Related
Change data in an array with N range steps, for instance, every 2 steps.
int data = new int[8];
result:
[0],[0], [0],[0], [0],[0], [0],[0];
expected:
The first two items should change to 1 and the next two will stay in 0 and so on...
[1],[1] ,[0],[0], [1],[1], [0],[0];
I know the trick with
if(position % 2 == 0)
for changing every 2 items but its changes only the first item.
any idea how to solve it?
int bars =2;
int beats = 4;
int[] pattern = new int[bars * beats];
for (int i = 0; i < pattern.length; i++) {
if(i % bars == 0 ){
pattern[i] = 0;
}else{
pattern[i] = 1;
}
}
Not the most elegant solution but works
static int[] data;
public static void main(String[] args) {
int bars = 7;
int beats = 2;
data = new int[bars * beats];
int minVal;
if(bars > beats){
minVal = Math.min(bars, beats);
}else{
minVal = Math.max(bars, beats);
}
step(minVal, 1);
for (int i = 0; i < data.length; i++) {
if(i % minVal == 0){
System.out.print("|"+ data[i]);
}else{
System.out.print(data[i]);
}
}
}
public static void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
static int[] data;
public static void main(String[] args) {
int bars = 7;
int beats = 2;
data = new int[bars * beats];
int minVal;
if(bars > beats){
minVal = Math.min(bars, beats);
}else{
minVal = Math.max(bars, beats);
}
step(minVal, 1);
for (int i = 0; i < data.length; i++) {
if(i % minVal == 0){
System.out.print("|"+ data[i]);
}else{
System.out.print(data[i]);
}
}
}
public static void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
Try this
int bars = 2;
int beats = 4;
int[] pattern = new int[bars * beats];
for (int i = 0; i < pattern.length; i++) {
if(i % beats < bars ){
pattern[i] = 1;
} else {
pattern[i] = 0;
}
}
This is 1 of many ways how you can achieve this. We loop through the array, incrementing by the defined interval, which you want to be 2 for example. We create another for-loop starting at the current index and end at current index + interval which will allow us to assign the value, in your case, 1, to those indices. We also check to see if the current index we're looping through is greater than the data length - 1 to ensure no array index out of bonds for non-even array sizes.
public class ChangeArrayNSteps {
public static void main(String[] args) {
ChangeArrayNSteps cans = new ChangeArrayNSteps(8);
cans.step(2, 1);
System.out.println("Data: " + Arrays.toString(cans.data));
}
private final int[] data;
public ChangeArrayNSteps(int size) {
this.data = new int[size];
}
public void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
}
Output:
Data: [1, 1, 0, 0, 1, 1, 0, 0]
Check if there exists a Palindrome Number in the list.
If found return its size, else return -1.
public class Program{
public static boolean palindrome(String list){
String reversedString = "";
for (int i = list.length() -1; i >=0; i--){
reveresedString += list.charAt(i)
}
return list.equals(revereseString);
}
}
sample input: [3,5,2,6,3,6,2,1]
palindrome number found: [2,6,3,6,2]
sample output: 5
Here is a pseudo code.
output = -1;
for (i = 0; i < list.length; i++){
num = list[i];
indices[] = \\ get all the indices which the "num" value appears, only include those indices that are greater than "i"
for (j = 0; j < indices.length; j++){
flag = true;
k = i;
for (l = indices[j]; l >= k; l--, k++){
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag){
length = (indices[j] - i) + 1;
if (length != 1 && length > output) { // checking of length != 1 will exclude those palindromes of length 2
output = length;
}
}
}
}
return output;
Here is the full code.
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
int[] list = { 3, 5, 2, 2, 6, 3, 6, 3, 6, 3, 6, 2, 2, 1 };
System.out.print(palindrome(list));
}
public static int palindrome(int[] list) {
int output = -1;
for (int i = 0; i < list.length; i++) {
int num = list[i];
ArrayList<Integer> indices = getIndices(list, i, num);
for (int j = 0; j < indices.size(); j++) {
boolean flag = true;
int k = i;
for (int l = indices.get(j); l >= k; l--, k++) {
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag) {
int length = (indices.get(j) - i) + 1;
if (length != 1 && length > output) {
output = length;
}
}
}
}
return output;
}
public static ArrayList<Integer> getIndices(int[] list, int start, int num) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = start + 1; i < list.length; i++) {
if (list[i] == num) {
result.add(i);
}
}
return result;
}
}
I'm trying to execute this so that it prints out the longest sequence of the same number. The error I get is that it's telling me that a class or enum is expected. Here's my code:
public class D4 {
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 6, 6, 45, 2, 2, 2};
System.out.println(getLongestRun(array));
}
}
This belongs as a comment, but I will give you full code so that it is clear. Just return max at the end of your getLongestRun() method:
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
// you forgot to return the length of the longest sequence to the caller
return max;
}
function getLongestRun() is missing return max; statement.
Write a method that takes an array of integers and returns the length of its longest subarray with distinct integers.
e.g. with [1,2,3,4,2,3] it should return 4.
I used a HashSet to keep track of all elements from index i to index j and kept a counter while traversing through the list. Linear runtime and space:
public static int longestSubarray(int[] arr) {
int i = 0, j = 1, max = 0, currLength = 1;
max = Math.max(max, currLength);
HashSet<Integer> set = new HashSet<Integer>();
set.add(arr[0]);
while (i < arr.length - 1 && j < arr.length) {
if (!set.contains(arr[j])) {
currLength++;
set.add(arr[j++]);
}
else {
set.remove(arr[i++]);
currLength--;
}
}
return Math.max(currLength, max);
}
public int[] getLargestSubArray(int[] array) {
int length = array.length;
Set<Integer> set = new HashSet<>();
int longest = 0;
int start = 0;
int longestCurrent = 0;
int startCurrent = 0;
int j = 0;
while (j < length) {
if (!set.contains(array[j])) {
set.add(array[j]);
longestCurrent++;
if (longestCurrent > longest) {
longest = longestCurrent;
start = startCurrent;
}
j++;
} else {
while (startCurrent < j) {
longestCurrent--;
if (array[startCurrent++] == (array[j])) {
break;
}
}
set.remove(array[j]);
}
}
int[] longestSubSequence = new int[longest];
System.arraycopy(array, start, longestSubSequence, 0, longest);
return longestSubSequence;
}
public static int sizeOfLongestDistinctSubArrayO1(int[] arr) {
int max = 0;
Map<Integer, Integer> counts = new HashMap<>();
int cur = 0;
int prev = 0;
for (int i = 0, len = arr.length; i < len; i++) {
if (counts.containsKey(arr[i])) {
int j = counts.get(arr[i]);
max = Math.max(max, cur);
prev = Math.max(j, prev);
cur = i - prev;
counts.put(arr[i], i);
} else {
cur++;
counts.put(arr[i], i);
}
}
return Math.max(max, cur);
}
python version
#!/usr/bin/env python3
input = [1,2,3,4,2,3,4,5,6,7,3,4]
tmp_list = []
max = 0
for i in input:
if i not in tmp_list:
tmp_list.append(i)
else:
max = len(tmp_list) if len(tmp_list) > max else max
tmp_list = [i]
print (max if max >= len(tmp_list) else len(tmp_list))
public int lengthOfLongestSubarray(int[] arr) {
int max = 0; // Maximum length of subarray with unique elements
Map<Integer,Integer> map = new HashMap<>();
// let longest subarray starts at i and ends at j
for(int i = -1,j = 0; j < arr.length;j++) {
if(map.containsKey(arr[j])) {
i = Math.max(i,map.get(arr[j]));
}
max = Math.max(max,j-i);
map.put(arr[j],j);
}
return max;
}
C# Version
Core Logic:
private static int Solve(string s) {
var dict = new Dictionary < string,int > ();
var arr = s.Split(" ", StringSplitOptions.RemoveEmptyEntries);
var start = 0;
var substrLen = 0;
for (var i = 0; i < arr.Length; i++) {
if (dict.ContainsKey(arr[i])) {
substrLen = substrLen < i - start ? i - start: substrLen;
var tempStart = dict[arr[i]] + 1;
for (var j = dict[arr[i]]; j > start; j--) {
dict.Remove(arr[i]);
}
start = tempStart;
dict[arr[i]] = i;
}
else {
dict.Add(arr[i], i);
}
}
return dict.Count;
}
Complete code here
import java.util.*;
class GFG{
static int largest_subarray(int a[], int n)
{
HashSet<Integer> set = new HashSet<Integer>();
int ans = 0;
int counter = 0;
for(int i = 0; i < n; i++)
{
if(set.contains(a[i])){
set.clear();
counter =0;
}
set.add(a[i]);
counter++;
ans = Math.max(ans, counter);
}
// Return final ans
return ans;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4
};
int n = arr.length;
System.out.print(largest_subarray(arr, n));
}
}
I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f