QuickSort implementation not working for large input - quicksort

Can anyone tell me why my quickSortHelper function doesn't solve for large input?
import java.util.*;
class Program {
public static int[] quickSort(int[] array) {
// Write your code here.
quickSortHelper(array, 0, array.length - 1);
return array;
}
public static void quickSortHelper(int[] array, int l, int r){
if(l >= r){
return;
}
int pivot = l;
int leftIndex = l + 1;
int rightIndex = r;
while(rightIndex >= leftIndex ){
if(array[leftIndex] > array[pivot] && array[rightIndex] < array[pivot]){
swap(leftIndex, rightIndex, array);
}
if(array[leftIndex] <= array[pivot]){
leftIndex += 1;
}
if(array[rightIndex] >= array[pivot]){
rightIndex -= 1;
}
}
swap(pivot, rightIndex, array);
boolean leftSubarrayIsSmaller = rightIndex - 1 - l < r - (rightIndex + 1);
if(leftSubarrayIsSmaller){
quickSortHelper(array, rightIndex + 1, l);
quickSortHelper(array, l, rightIndex - 1);
}else{
quickSortHelper(array, l, rightIndex - 1);
quickSortHelper(array, rightIndex + 1, l);
}
}
public static void swap(int i, int j, int[] array){
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
Here's my test case, I think if I solve for this it will be an efficient implementation.
int[] array7 = {-4, 5, 10, 8, -10, -6, -4, -2, -5, 3, 5, -4, -5, -1, 1, 6, -7, -6, -7, 8};
The current result is as follows
[-10, -7, -6, -7, -6, -5, -4, -5, -4, 3, 5, -4, -2, -1, 1, 6, 8, 10, 5, 8]
As you can see, still not completely sorted. This does work for smaller input, as in less than 10 numbers.
Any help would be highly appreciated!
Cheers,

You have two lines that look like this, and they do nothing:
quickSortHelper(array, rightIndex + 1, l);
Replace the l with an r:
quickSortHelper(array, rightIndex + 1, r);

Related

how to calculate sum of every n values in a list?

I have a list that contains some values I want to calculate the sum of every 4 items in this list and then I have to put it in a list.
for example:
list 1=[1,2,3,4,5,6,7,8]
output= [10,26]
You can play with snippet.
final List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List<List<int>> subLists = [];
for (int i = 0; i < list.length / 4; i++) {
final start = i * 4;
final end = i * 4 + 4;
subLists
.add(list.sublist(start, end > list.length ? list.length : end));
}
print(subLists); //[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
final results = subLists
.map((l) => l.reduce((value, element) => value + element))
.toList();
print(results); //[10, 26, 9]
You can use this custom-made extension method to sum every n in a `List``, just add it inside your file outside your classes :
extension SumEveryExtension on List<num> {
List<num> sumEvery(int n) {
num nSumTracker = 0;
List<num> result = [];
for (int index = 0; index < length; index += 1) {
nSumTracker += this[index];
print("current" + nSumTracker.toString());
if ((index +1) % (n ) == 0 && index != 0) {
result.add(nSumTracker);
nSumTracker = 0;
}
}
return result;
}
}
And use it in your code like this:
List<int> list = [1, 2, 3, 4, 5, 6, 7, 8];
print(list.sumEvery(4)); // [10, 26]
You can also customize the n from the method to sum for any other n.

find only same value of that closest to the current index element in an array dart/flutter

I have an array that have same value, so i want to like filter it only for same value that closest to the current index, example :
A[0] = 2,
A[1] = -2,
A[2] = -2,
A[3] = 9,
A[4] = 9,
A[5] = 9,
A[6] = 4,
A[7] = -2,
A[8] = -2,
A[9] = -2,
i want my code can find that the index 1 2 is have same value which is -2 with length 2,
index 3 4 5 have same value 9 with length 3
and index 7 8 9 have same value -2 with length 3 and my code will return only the length of the most in the same value range and closest to index 0 which is value 9
void main() {
var nInt = <ArrayA>[
ArrayA(e: 'A', n: 2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: -1),
ArrayA(e: 'A', n: 7),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
for (var i = 0; i < nInt.length; i++) {
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
} else {
break;
}
}
];
class ArrayA {
final String e;
final int n;
ArrayA({this.e, this.n});
#override
String toString() {
return '$n';
}
}
In-order to achieve that, you need to store the comparison result and nearest index somewhere. For this purpose you can create a class like:
class Counter {
final int index;
final int number;
final int count;
Counter({required this.index, required this.number, required this.count});
#override
String toString() {
return '$count times $number at $index';
}
}
And change the logic to:
var counterValues = <Counter>[];
for (var i = 0; i < nInt.length; i++) {
int count = 1;
int value = nInt[i].n;
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
count += 1;
} else {
// Break the inner loop and go to next outer-loop iteration
// You can optimise this by skipping already checked positions (ie: Update i)
break;
}
}
counterValues.add(Counter(index: i, count: count, number: value));
}
And finally to find the most recurring nearest value, you can use the reduce:
var result =
counterValues.reduce((a, b) => (a.count >= b.count && a.index < b.index) ? a : b);
print(result); // Output: 3 times 9 at 3

How to check and calculate full house of dice

I'm making a Yahtzee-like game with 5 dices using Flutter + Dart. I keep the dice values in a List<int>. What would be the best way to check if there is a full house, and what is the sum or relevant dices?
If I want only to determine if I have a full house, this solution would be good. But I have to calculate the sum afterwards, so I need to know how many of which numbers I have.
Making 30 ifs to cover each case is a solution, but probably not the best one. Does anyone have any better idea?
Here would be a simple Dart implementation using List/Iterable methods:
bool fullHouse(List<int> dice) {
final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
dice.forEach((n) => counts[n]++);
return counts.containsValue(3) && counts.containsValue(2);
}
int diceSum(List<int> dice) => dice.reduce((v, e) => v + e);
As you can see, I separated the sum and the full house check, but I can also adjust this if necessary.
Extension
If you are using a Dart 2.6 or later, you could also create a nice extension for this:
void main() {
print([1, 1, 2, 1, 2].fullHouseScore);
}
extension YahtzeeDice on List<int> {
int get fullHouseScore {
if (isFullHouse) return diceSum;
return 0;
}
bool get isFullHouse {
final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
forEach((n) => counts[n]++);
return counts.containsValue(3) && counts.containsValue(2);
}
int get diceSum => reduce((v, e) => v + e);
}
Testing
This would be a simple usage of the functions for testing:
int checkFullHouse(List<int> dice) {
if (fullHouse(dice)) {
final sum = diceSum(dice);
print('Dice are a full house. Sum is $sum.');
return sum;
} else {
print('Dice are not a full house.');
return 0;
}
}
void main() {
const fullHouses = [
[1, 1, 1, 2, 2],
[1, 2, 1, 2, 1],
[2, 1, 2, 1, 1],
[6, 5, 6, 5, 5],
[4, 4, 3, 3, 3],
[3, 5, 3, 5, 3],
],
other = [
[1, 2, 3, 4, 5],
[1, 1, 1, 1, 2],
[5, 5, 5, 5, 5],
[6, 5, 5, 4, 6],
[4, 3, 2, 5, 6],
[2, 4, 6, 3, 2],
];
print('Testing dice that are full houses.');
fullHouses.forEach(checkFullHouse);
print('Testing dice that are not full houses.');
other.forEach(checkFullHouse);
}
Why not just use the linked solution?
bool isFullHouse(List<int> diceResults) {
String counterString = diceResults.map((i) => i.toString()).join();
return RegExp('20*3|30*2').hasMatch(counterString);
}
int getDiceSum(List<int> diceResults) {
int sum = 0;
for (int i = 0; i < 6; i++) {
sum += [0, 0, 2, 0, 3, 0][i] * (i + 1);
}
return sum;
}
// elsewhere
dice = [0, 0, 2, 0, 3, 0]; // example result
if (isFullHouse(dice)) {
int score = getDiceSum(dice);
// Do something with sum
}

scala for loop issue with assignment

val u = Array(1,2,3,4,5)
var outsideValue = 7
for{
i <- 0 until u.size
_= outsideValue = u(i)
if(outsideValue == 2)
j <- u
}
{
println(s"$outsideValue $j")
`Expected output is it should print all combination of Array with value 2, but it is not printing !!!`
NOTE: I know we can do it in simpleway
But i want to know why above code is not working
Let us first start with how will you do this in any other language,
Java
String[] u = {1, 2, 3, 4, 5};
for (int i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (int j = 0; j < u.length(); j++) {
System.out.println("" + u[i] + ", " + u[j]);
}
}
}
JavaScript,
var u = [1, 2, 3, 4, 5];
for (var i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (var j = 0; j < u.length(); j++) {
console.log("" + u[i] + ", " + u[j]);
}
}
}
And you can do it the more or less same way in Scala with for-loop. (Not to be confused with the concept of for-comprehension)
val u = new Array(1, 2, 3, 4, 5)
for (i <- 0 until u.length()) {
if (u(i) == 2) {
for (j <- 0 until u.length()) {
println(s"${u(i)}, ${u(j)})
}
}
}
If you want to use for-comprehension then,
val u = Array(1, 2, 3, 4, 5)
for {
i <- u.filter(_ == 2)
j <- u
} println(s"$i, $j")
As for "why your code does not work ?". The reason is that you are trying to use for-comprehension without really understanding these, which lead to a very strange looking and incorrect code.
for-comprehension in Scala works by using combinations of map / flatMap / foreach / flatten in various ways depending on the usage.
In this case, the above for-comprehension version is equivalent to the following foreach based version,
val array = Array(1, 2, 3, 4, 5)
array.filter(_ == 2).foreach(i => {
array.foreach(j => println(s"$i, $j")
})

MaxSubArray using dynamic style

I have been trying to create code that counts the max substring from array and returns sum and starting and ending point. I have some error in there however that I cannot spot because for example when I use Array(-2, 1, -3, 4, -1, 2, 1, -5, 4) as source I get return (7, 5,8). However, the correct answer should be (6, 3, 6). Code below.
def solve(a: Array[Int]): (Int, Int, Int) = {
require(a.nonEmpty)
val n = a.length
val temp = Array.fill(n)(0, 0, 0)
var max = (0,0,0) // sum, start, end
for (i <- 0 to n-1) {
temp(i) = (a(i), i, i)
}
for (i <- 0 to n-1) {
for (j <- 0 to i) {
if (a(i) > a(j) && temp(i)._1 < temp (j)._1 + a(i)) {
temp(i) = (temp(j)._1 + a(i), j, i)
}
}
}
for (i <- 0 to n-1){
if (max._1 < temp(i)._1){
max = temp(i)
}
}
return max
}
How about a more Scala/functional approach?
def solve(a: Array[Int]): (Int, Int, Int) = {
a.tails.zipWithIndex.flatMap{
case (arr, ti) =>
arr.inits.map{
tail => (tail.sum, ti, ti + tail.length -1)
}
}.maxBy(_._1)
}
solve (Array(-2, 1, -3, 4, -1, 2, 1, -5, 4)) => res7: (Int, Int, Int) = (6,3,6)