the permutations of some numbers, especially some common numbers in input - numbers

just like the input is : 1,2,2,3,4,5. I have to work out all the permutations of these numbers, just pay attention that 2 is a duplicate number.
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}

Related

Descending Quicksort in Solidity

I cannot find a descending quicksort for Solidity, this is my code based on this gist but is on ascending order: https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f
function quickSort(uint[] memory arr, int left, int right) internal pure {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
It was easier than I thought. Had to change only the comparing relating to pivot:
function quickSort(uint[] memory arr, int left, int right) internal pure {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] > pivot) i++;
while (pivot > arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}

coq Basics: bin_to_nat function

I am passing Logical Foundations course and became stuck upon the last excersize of Basics:
Having binary number write a converter to it's unary representation:
Inductive bin : Type :=
| Z
| A (n : bin)
| B (n : bin).
Fixpoint bin_to_nat (m:bin) : nat :=
(* What to do here? *)
I solved the problem with a recursive function in C. The only thing, I used "0" istead of "A" and "1" instead of "B".
#include <stdio.h>
unsigned int pow2(unsigned int power)
{
if(power != 0)
return 2 << (power - 1);
else
return 1;
}
void rec_converter(char str[], size_t i)
{
if(str[i] == 'Z')
printf("%c", 'Z');
else if(str[i] == '0')
rec_converter(str, ++i);
else if(str[i] == '1')
{
unsigned int n = pow2(i);
for (size_t j = 0; j < n; j++)
{
printf("%c", 'S');
}
rec_converter(str, ++i);
}
}
int main(void)
{
char str[] = "11Z";
rec_converter(str, 0);
printf("\n");
return 0;
}
My problem now is how to write this code in coq:
unsigned int n = pow2(i);
for (size_t j = 0; j < n; j++)
{
printf("%c", 'S');
}
rec_converter(str, ++i);
The main difference between your code and the Coq code is that the Coq code ought to return the natural number, rather than printing it. That means we'll need to keep track of everything that your solution printed and return the result all at once.
Since printing an S means that the answer is the successor of whatever else is printed, we'll need a function that can take the 2^(n)th successor of a natural number. There are various ways to do this, but I'd suggest recursion on n and noting that the 2^(n + 1)th successor of x is the 2^(n)th successor of the 2^(n)th successor of x.
That should be enough to get what you want.
unsigned int n = pow2(i);
for (size_t j = 0; j < n; j++)
{
printf("%c", 'S');
}
rec_converter(str, ++i);
can be written (in pseudo-Coq) as
pow2_succ i (rec_converter str (S i)).
However, one other thing to note: you may not be able to directly access the ith "character" of the input, but this shouldn't be a problem. When you write your function as a Fixpoint
Fixpoint rec_converter (n: bin) (i: nat): nat :=
match n with
| Z => 0
| A m => ...
| B m => ...
end.
the first "character" of m will be the second "character" of the original input. So you'll just need to access the first "character", which is exactly what a Fixpoint does.
For the question on computing powers of 2, you should look at the following file, provided in the Coq libraries (at least up to version 8.9):
https://coq.inria.fr/distrib/current/stdlib/Coq.Init.Nat.html
This file contains a host of functions around the natural numbers, they could all be used as illustrations about how to program with Coq and this datatype.
Fixpoint bin_to_nat (m:bin) : nat :=
match m with
| Z => O
| A n =>2 * (bin_to_nat n)
| B n =>2 * (bin_to_nat n) + 1
end.
see: coq art's 2004. P167-P168. ( How to understand 'positive' type in Coq)

Best purely functional alternative to a while loop

Is the a better functional idiom alternative to the code below? ie Is there a neater way to get the value j without having to use a var?
var j = i + 1
while (j < idxs.length && idxs(j) == x) j += 1
val j = idxs.drop(i).indexWhere(_ != x) + i
Or, as suggested by #kosii in the comments, use the indexWhere overload that takes an index from where to start searching:
val j = idxs.indexWhere(_ != x, i)
Edit
Since j must equal the length of idxs in case all items following i are equal to x:
val index = idxs.indexWhere(_ != x, i)
val j = if(index < 0) idxs.length else index
// or
val j = if (idxs.drop(i).forall(_ == x)) idxs.length
else idxs.indexWhere(_ != x, i)
Maybe with streams, something like:
((i + 1) to idxs.length).toStream.takeWhile(j => idxs(j) == x).last

Scala constructing a "List", read from stdin, output to stdout

I'm trying to read formatted inputs from stdin using Scala:
The equivalent C++ code is here:
int main() {
int t, n, m, p;
cin >> t;
for (int i = 0; i < t; ++i) {
cin >> n >> m >> p;
vector<Player> players;
for (int j = 0; j < n; ++j) {
Player player;
cin >> player.name >> player.pct >> player.height;
players.push_back(player);
}
vector<Player> ret = Solve(players, n, m, p);
cout << "Case #" << i + 1 << ": ";
for (auto &item : ret) cout << item.name << " ";
cout << endl;
}
return 0;
}
Where in the Scala code, I'd like to Use
players: List[Player], n: Int, m: Int, p: Int
to store these data.
Could someone provide a sample code?
Or, just let me know how to:
how the "main()" function work in scala
read formatted text from stdin
efficiently constructing a list from inputs (as list are immutable, perhaps there's a more efficient way to construct it? rather than having a new list as each element comes in?)
output formatted text to stdout
Thanks!!!
I don't know C++, but something like this should work :
def main(args: Array[String]) = {
val lines = io.Source.stdin.getLines
val t = lines.next.toInt
// 1 to t because of ++i
// 0 until t for i++
for (i <- 1 to t) {
// assuming n,m and p are all on the same line
val Array(n,m,p) = lines.next.split(' ').map(_.toInt)
// or (0 until n).toList if you prefer
// not sure about the difference performance-wise
val players = List.range(0,n).map { j =>
val Array(name,pct,height) = lines.next.split(' ')
Player(name, pct.toInt, height.toInt)
}
val ret = solve(players,n,m,p)
print(s"Case #${i+1} : ")
ret.foreach(player => print(player.name+" "))
println
}
}

Need pointers for optimization of Merge Sort implementation in Scala

I have just started learning Scala and sideways I am doing some algorithms also. Below is an implementation of merge sort in Scala. I know it isn't very "scala" in nature, and some might even reckon that I have tried to write java in scala. I am not totally familiar with scala, i just know some basic syntax and i keep googling if i need something more. So please give me some pointers on to what can i do in this code to make it more functional and in accord with scala conventions and best practices. Please dont just give correct/optimized code, i will like to do it myself. Any suggestions are welcomed !
def mergeSort(list: Array[Int]): Array[Int] = {
val len = list.length
if (len == 1) list
else {
var x, y = new Array[Int](len / 2)
val z = new Array[Int](len)
Array.copy(list, 0, x, 0, len / 2)
Array.copy(list, len / 2, y, 0, len / 2)
x = mergeSort(x)
y = mergeSort(y)
var i, j = 0
for (k <- 0 until len) {
if (j >= y.length || (i < x.length && x(i) < y(j))) {
z(k) = x(i)
i = i + 1
} else {
z(k) = y(j)
j = j + 1
}
}
z
}
}
[EDIT]
This code works fine and I have assumed for now that input array will always be of even length.
UPDATE
Removed vars x and y
def mergeSort(list: Array[Int]): Array[Int] = {
val len = list.length
if (len == 1) list
else {
val z = new Array[Int](len)
val x = mergeSort(list.dropRight(len/2))
val y = mergeSort(list.drop(len/2))
var i, j = 0
for (k <- 0 until len) {
if (j >= y.length || (i < x.length && x(i) < y(j))) {
z(k) = x(i)
i = i + 1
} else {
z(k) = y(j)
j = j + 1
}
}
z
}
}
Removing the var x,y = ... would be a good start to being functional. Prefer immutability to mutable datasets.
HINT: a method swap that takes two values and returns them ordered using a predicate
Also consider removing the for loop(or comprehension).