How to find permutation of k in a given length? - language-agnostic

How can I find the permutations of k in a given length?
For example:
The word cat has 3 letters: How can I find all the permutations of 2 in the word cat.
Result should be: ac, at, ca, ac, etc...
This is not a homework problem.
Any language could be used but more preferable: C/C++ or C#.
I know how to create the recursion for size LENGTH but not for a custom size.

Here is one in C#, which should work even with repeated characters. For example on "banana" for permutations of length 2 it gives:
ba bn ab aa an nb na nn
The basic idea is to fix the first character, then form all permutations of length k-1, then prepend the character to those k-1 length permutations. To deal with duplicate characters, we keep track of the count left (i.e the ones which can be used for sub-permutations).
Not exemplary code, but should give you the idea. (If you find bugs, let me know and I can edit).
static List<string> Permutations(Dictionary<char, int> input, int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
// Base case.
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
// There are instances of this character left to use.
if (input[c] > 0) {
// Use one instance up.
input[c]--;
// Find sub-permutations of length length -1.
List<string> subpermutations = Permutations(input, length - 1);
// Give back the instance.
input[c]++;
foreach (string s in subpermutations) {
// Prepend the character to be the first character.
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
And here is the full program I have, to use it:
using System;
using System.Collections.Generic;
namespace StackOverflow {
class Program {
static void Main(string[] args) {
List<string> p = Permutations("abracadabra", 3);
foreach (string s in p) {
Console.WriteLine(s);
}
}
static List<string> Permutations(string s, int length) {
Dictionary<char, int> input = new Dictionary<char, int>();
foreach (char c in s) {
if (input.ContainsKey(c)) {
input[c]++;
} else {
input[c] = 1;
}
}
return Permutations(input, length);
}
static List<string> Permutations(Dictionary<char, int> input,
int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
if (input[c] > 0) {
input[c]--;
List<string> subpermutations = Permutations(input,
length - 1);
input[c]++;
foreach (string s in subpermutations) {
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
}
}

What's wrong with the recursive solution and passing an extra parameter (depth) so that the recursive function returns immediately for depth > n.

Not the most efficient, but it works:
public class permutation
{
public static List<string> getPermutations(int n, string word)
{
List<string> tmpPermutation = new List<string>();
if (string.IsNullOrEmpty(word) || n <= 0)
{
tmpPermutation.Add("");
}
else
{
for (int i = 0; i < word.Length; i++)
{
string tmpWord = word.Remove(i, 1);
foreach (var item in getPermutations(n - 1, tmpWord))
{
tmpPermutation.Add(word[i] + item);
}
}
}
return tmpPermutation;
}
}

void Prem (char *str, int k, int length) {
if (k == length-1){
printf("%s\n",str);
return;
} else {
for (int i = k ; i < length; ++i) {
char t = str[k];
str[k] = str[i];
str[i] = t;
Prem(str,k+1,length);
t = str[k];
str[k] = str[i];
str[i] = t;
}
}
}

If I'm not mistaken, this problem can be solved by combinadics too, as on http://en.wikipedia.org/wiki/Combinadic/, there are reference implementations there too.
I have used the Java solution (http://docs.google.com/Doc?id=ddd8c4hm_5fkdr3b/) myself for generating all possible triples from a sequence of numbers, this should be no different.
I lack the wherewithal to explain the math behind it, but as I understand this is the least complex way to iterate over all possible nCr (i.e. 3C2 for your cat example) choices within a collection.

First find the possible subsets of your array. You can do this in
a recursive way it was discussed in Iterating over subsets of any size
Second calculate the permutations of every subset with the STL-Algorithm
next_permutation
I haven't implemented it but i think it should work.

Related

element.length not working when using generics

My problem is this. I am passing arguments to a function that uses generics. For example I am passing element. I need to use element.length in the function but it gives me this error:
The property 'length' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!'). dartunchecked_use_of_nullable_value
void main(List<String> args) {
const List keyList = ['asd', 3, 'tyu', 67];
const List valueList = ['dfg', 'ert', 4, 'lkj'];
print(myMap(keyList, valueList));
}
Map myMap<K, V>(K key, V val) {
final Map<K, V> myMap = {};
for (int i = 0; i < key.length; i++) {
myMap[key[i]] = val[i];
}
return myMap;
}
I don't know if null aware operators can be used here, or if they solve the problem and how to use it.
You defined your generic types, but your parameters are lists of that type. You did not make this clear to your compiler. For your compiler, K is now of type List<dynamic> while what you wanted it to be is just dynamic.
Changing it to make it fit (my guess of) your requirements:
Map<K, V> myMap<K, V>(List<K> keys, List<V> values) {
final result = <K, V>{};
for (int i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
}
Please note that you are reinventing the wheel here. There already is a constructor that does this:
void main(List<String> args) {
const List keyList = ['asd', 3, 'tyu', 67];
const List valueList = ['dfg', 'ert', 4, 'lkj'];
print(Map.fromIterables(keyList, valueList));
}

How to set data pointed to by argument using Critcl?

I would like to express something like this in Critcl:
void setter(int* grid, int value, int x, int y) {
grid[xy2addr(x,y)] = value;
}
I'm in particular stuck on how to deal with int* grid in Critcl. object? bytes? Custom type maybe?
Related to this question.
This case doesn't map very well onto Tcl's value model. The issue is that grid is (a pointer to) an updateable value collection. There are two ways of modelling this in Tcl in general:
As an opaque object.
As a variable containing a Tcl list (since in model terms, while Tcl values are thought of as immutable, Tcl variables are mutable).
I'll describe how to do both below, but I'm guessing that you're going to be thinking of these zOrder things as a distinct mutable type and that the additional modest one-time overhead of making the custom type will suit you far better.
Opaque (Mutable) Objects
When working with opaque objects, you pass handles to them (basically just a name) around and then you unpack them as a custom Critcl type. The trick is to create some helper functions in C to do the mapping (this can be in a critcl::ccode command) that does the mapping between names and pointers. This is slightly messy to do, but is just about building a couple of hash tables.
critcl::ccode {
static Tcl_HashTable *zOrderMap = NULL, *zOrderRevMap = NULL;
static Tcl_Obj *
MakeZOrderObj(int *zOrder) {
/* Initialize the two maps, if needed */
if (zOrderMap == NULL) {
zOrderMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitObjHashTable(zOrderMap);
zOrderRevMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitHashTable(zOrderRevMap, TCL_ONE_WORD_KEYS);
}
int isNew;
Tcl_HashEntry *hPtr = Tcl_FindHashEntry(zOrderRevMap, (char*) zOrder, &isNew);
if (!isNew) {
return Tcl_GetHashValue(hPtr);
}
/* make a handle! */
Tcl_Obj *handle = Tcl_ObjPrintf("zOrder%ld", (long) zOrder);
Tcl_SetHashValue(hPtr, handle);
Tcl_IncrRefCount(handle);
hPtr = Tcl_CreateHashEntry(zOrderMap, (char*) handle, &isNew);
Tcl_SetHashValue(hPtr, zOrder);
return handle;
}
static int
GetZOrderFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, int **zOrderPtr) {
Tcl_HashTable *hPtr;
if (!zOrderMap || (hPtr = Tcl_FindHashEntry(zOrderMap, (char *) objPtr)) == NULL) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf("no such zOrder \"%s\"",
Tcl_GetString(objPtr)));
return TCL_ERROR;
}
*zOrderPtr = (int *) Tcl_GetHashValue(hPtr);
return TCL_OK;
}
}
With that helper code in place, you can then define a custom Critcl type like this:
critcl::argtype zOrder {
if (GetZOrderFromObj(interp, ##, #A) != TCL_OK) {
return TCL_ERROR;
}
} int*
critcl::resulttype zOrder {
if (rv == NULL) {
return TCL_ERROR;
}
Tcl_SetObjResult(interp, MakeZOrderObj(rv));
return TCL_OK;
} int*
That then lets you write your real code as something like this. Note that grid is defined as being of (custom) type zOrder, and that those can only be manufactured by some code that returns a zOrder as its result.
critcl::cproc setter {zOrder grid int value int x int y} void {
grid[xy2addr(x,y)] = value;
}
(The deletion function that removes the entries from the hash tables and deletes the C array is left as an exercise.)
Tcl List Variable
The other way of doing this is to make zOrder values be held in Tcl variables as lists of integers. This can be nice because it lets you look inside easily, but it can also be not so nice in other ways, as the code is not constrained to work with proper values and you expose your cprocs to more details of what's happening in Tcl.
critcl::cproc setter {Tcl_Interp* interp object varName int value int x int y} ok {
/* Unpack the list of ints from the variable */
Tcl_Obj *listObj = Tcl_ObjGetVar2(interp, varName, NULL, TCL_LEAVE_ERR_MSG);
if (listObj == NULL)
return TCL_ERROR;
Tcl_Obj **listv; int listc;
if (Tcl_ListObjGetElements(interp, listObj, &listc, &listv) != TCL_OK)
return TCL_ERROR;
int *grid = alloca(sizeof(int) * listc);
for (int i=0; i<listc; i++)
if (Tcl_GetIntFromObj(interp, listv[i], &grid[i]) != TCL_OK)
return TCL_ERROR;
/* The core of the functionality */
grid[xy2addr(x,y)] = value;
/* Repack the list of ints from the variable; this code could be optimized in this case! */
for (int i=0; i<listc; i++)
listv[i] = Tcl_NewIntObj(grid[i]);
listObj = Tcl_NewListObj(listc, listv);
Tcl_ObjSetVar2(interp, varName, NULL, listObj, 0);
return TCL_OK;
}

Monospaced html formatting jlabel

I am creating an output window for a program dealing with matrices. It is supposed to print out the preformed command along with a formatted version of the matrix. But I am having problems with the alignment. I know the String.format works because i have a toString() method that works correctly.
Notice how the second and third rows are not correctly spaced. This is because the 100.00 has completely filled the formatted string where as the 0.00's need extra spaces to fill the string(see toHtml()). I believe this has something to do with the way that the HTML is being displayed but im not sure. My guess is that the spaces behind the zeros are not being displayed properly or are being combined.
Here are the methods involved.
public String toHtml(int dec)
{
String[] colors = {"#C0C0C0","#FFFFFF"};
String f = "%-"+(getLongestValue()+dec+1)+"."+dec+"f";
String res = "";
for(int r = 0;r<rows;r++)
{
for(int c = 0;c<columns;c++)
{
res += "<span style=\"background-color:"+colors[(r+c)%2]+";\">"+String.format(f, contents[r][c])+"</span>";
}
res += "<p>";
}
return res;
}
which creates the HTML text to be displayed. The method getLongestValue() returns the largest length of any number before its decimal place in the array 'contents'.
and
newOutput("New Matrix ["+name+"]<br>"+m.toHtml());
public void newOutput(String s)
{
JLabel l = new JLabel("<html>"+s+"<br></html>");
l.setFont(new Font("Monospaced",1,18));
jPanel1.add(l);
}
which adds the label to the output window
Also, here is the toString() method for reference
public String toString()
{
String f = "%-"+(getLongestValue()+3)+".2f ";
String res = "";
for(int r = 0;r<rows;r++)
{
for(int c = 0;c<columns;c++)
{
res += String.format(f, contents[r][c]);
}
res += "\n";
}
return res;
}
output of the Matrix through toString()
toString Output
A more extreme version
In this case the program should have found that the largest values were -15 or -20 and set the size of the format length to 6( 3 for the length, 2 for the decimal places and 1 for the decimal) but instead it doesnt appear that any of the values, besides the two I mentioned, are following the format.
Here is the output of toString() for the previous example
toString() output
This fixes it, the spaces arent being represented correctly as monospaced
public String toHtml(int dec)
{
String[] colors = {"#C0C0C0","#FFFFFF"};
String f = "%-"+(getLongestValue()+dec+2)+"."+dec+"f";
String res = "";
for(int r = 0;r<rows;r++)
{
for(int c = 0;c<columns;c++)
{
res += "<span style=\"background-color:"+colors[(r+c)%2]+";\">"+
String.format(f, contents[r][c]).replaceAll("\\s", ((char)160)+"")+"</span>";
}
res += "<p>";
}
return res+"";
}

making function is number is odd or even

I want to make a function to find a number is odd or even by using only increment or decrement function . no another operator like equal or modular operator
def isOdd(n:Int) = {
if(n <= 1) n;
else isOdd(n - 2);
}
this will return 1 or 0 (true or false) whether or not the number n is odd.
I forgot to mention that this code is runnable in Scala.
It's tail-recursive, too.
check something like this with % mod operator
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsOdd(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
}
Maybe something like this? This solution however does use assignment and logical operators.
var isEven = true;
function makeDivayanshusHomework (number) {
if (number < 0) {
for(i = 0; i < 2*number; i++) {
number++;
}
}
while (number > 0) {
number--;
isEven = isEven ? false : true;
}
return isEven;
}
edit: as per sascha10000's comments, the solution below is perhaps even somewhat more functional:
function makeDivayanshusHomework (number) {
if (Math.sqrt(number*number) > 1) {
return makeDivayanshusHomework(number-2)
}
else {
return Math.sqrt(number*number); // 1 when odd, 0 otherwise
}
}
which brings me almost to sascha10000's original answer, although this method gracefully handles negative integers. Did your teacher specify to what extent the input has to be sanitised?
perhaps
public bool isEven(int number){
return number/2.0 == Convert.ToInt32(number/2.0)
}
I'm not quite sure how you intend to test a number for being even without an equals or mod operator.
Lucas

How to adress elements of a recursive function?

Take a recursive function, say:
public static long rekurs(long n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 1;
} else {
return rekurs(n - 1)*(rekurs(n - 2)+4;
}
}
When n=20, the function has to find all the values S(n) for n=2,...,19 first.
When I let n go from 20 to 21, it does the same thing again (plus finding S(20)).
Now I want to create an array, in which the found values S(n) for n=2,...,19 are filled into, so that the function for n=21 does not have to do the same thing again, but how do I get those elements?
This is the solution I figured out, it's a little bit different from the lecture example.
The keyword that helped me is "dynamic programming".
import java.util.Arrays;
public class Bsp13 {
public static final int N = 0;
public static final int Ende = 20;
public static long[] schroe = new long[N + Ende + 1];
public static void main(String[] args) {
schroe[0] = 1;
schroe[1] = 1;
for (int n = 2; n <= Ende + N; n++) {
schroe[n] = ((6 * n - 3) * (schroe[n-1]) - (n - 2) * (schroe[n-2])) / (n + 1);
}
System.out.println(schroe[N]);
System.out.println(Arrays.toString(schroe));
System.out.println(schroe[N+Ende]);
}
}
What you are trying to do is called dynamic programming. Basically it is bookkeeping in order to not compute subsolutions more than once.
So basically, you need a mapping of n values to solution values. I would suggest you use a dictionary-like-datastructure for this task.
When a value for n needs to be computed, you first check whether the solution is in the dictionary, if yes you return the result. If not, you compute the result and put it into the dictionary.
Think about how you would initialize this dictionary and how you would pass it down to the recursive function calls.
Here's a lecture video on dynamic programming where the computation of Fibonnaci-numbers using dynamic programming is explained, which is very similar to what you are trying to do:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-19-dynamic-programming-i-fibonacci-shortest-paths/