use an int and params as an argument - function

-hi, i have this function:
public static void conversion(int number ,params int [] tab)
-i tried to do the division of the number on each int in tab and put the results of each division in an arraylist then reverse it after that i put in a string
it didn't work
-i tried it like this
public static string Conversion(int number,params int [] tab)
{ ArrayList nbr = new ArrayList();
string Sconversion = string.Empty;
int b;
b = number;
for (int i=0;i<tab.Length;i++)
{
int reste;
do
{
reste = number % tab[i];
number = number / tab[i];
nbr.Add(reste);
} while (number != 0);
nbr.Reverse();
number = b;
for(int j = 0; j < nbr.Count ; j++) {
Sconversion += nbr[j];
}
}

Related

C# How to count how many anagrams are in a given string

I have to calculate how many anagrams are in a given word.
I have tried using factorial, permutations and using the posibilities for each letter in the word.
This is what I have done.
static int DoAnagrams(string a, int x)
{
int anagrams = 1;
int result = 0;
x = a.Length;
for (int i = 0; i < x; i++)
{ anagrams *= (x - 1); result += anagrams; anagrams = 1; }
return result;
}
Example: for aabv I have to get 12; for aaab I have to get 4
As already stated in a comment there is a formula for calculating the number of different anagrams
#anagrams = n! / (c_1! * c_2! * ... * c_k!)
where n is the length of the word, k is the number of distinct characters and c_i is the count of how often a specific character occurs.
So first of all, you will need to calculate the faculty
int fac(int n) {
int f = 1;
for (int i = 2; i <=n; i++) f*=i;
return f;
}
and you will also need to count the characters in the word
Dictionary<char, int> countChars(string word){
var r = new Dictionary<char, int>();
foreach (char c in word) {
if (!r.ContainsKey(c)) r[c] = 0;
r[c]++;
}
return r;
}
Then the anagram count can be calculated as follows
int anagrams(string word) {
int ac = fac(word.Length);
var cc = countChars(word);
foreach (int ct in cc.Values)
ac /= fac(ct);
return ac;
}
Answer with Code
This is written in c#, so it may not apply to the language you desire, but you didn't specify a language.
This works by getting every possible permutation of the string, adding every copy found in the list to another list, then removing those copies from the original list. After that, the count of the original list is the amount of unique anagrams a string contains.
private static List<string> anagrams = new List<string>();
static void Main(string[] args)
{
string str = "AAAB";
char[] charArry = str.ToCharArray();
Permute(charArry, 0, str.Count() - 1);
List<string> copyList = new List<string>();
for(int i = 0; i < anagrams.Count - 1; i++)
{
List<string> anagramSublist = anagrams.GetRange(i + 1, anagrams.Count - 1 - i);
var perm = anagrams.ElementAt(i);
if (anagramSublist.Contains(perm))
{
copyList.Add(perm);
}
}
foreach(var copy in copyList)
{
anagrams.Remove(copy);
}
Console.WriteLine(anagrams.Count);
Console.ReadKey();
}
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
{
var temp = string.Empty;
foreach(var character in arry)
{
temp += character;
}
anagrams.Add(temp);
}
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
Final Notes
I know this isn't the cleanest, nor best solution. This is simply one that carries the best across the 3 object oriented languages I know, that's also not too complex of a solution. Simple to understand, simple to change languages, so it's the answer I've decided to give.
EDIT
Here's the a new answer based on the comments of this answer.
static void Main(string[] args)
{
var str = "abaa";
var strAsArray = new string(str.ToCharArray());
var duplicateCount = 0;
List<char> dupedCharacters = new List<char>();
foreach(var character in strAsArray)
{
if(str.Count(f => (f == character)) > 1 && !dupedCharacters.Contains(character))
{
duplicateCount += str.Count(f => (f == character));
dupedCharacters.Add(character);
}
}
Console.WriteLine("The number of possible anagrams is: " + (factorial(str.Count()) / factorial(duplicateCount)));
Console.ReadLine();
int factorial(int num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
}

Cuda Implementation of Partitioned Subgroup

is there a more efficient way to implement the "Partitioned Subgroup" functions of Vulkan/OpenGL, which do not have to loop over all elements in the subgroup? My current implementation just uses a loop from 0 to WARP_SIZE.
References:
(slide 37+38) https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9909-nvidia-vulkan-features-update.pdf
https://github.com/KhronosGroup/GLSL/blob/master/extensions/nv/GL_NV_shader_subgroup_partitioned.txt
Simple Implementation:
__device__ uint32_t subgroupPartitionNV(ivec2 p)
{
uint32_t result = 0;
for (int i = 0; i < 32; ++i)
{
int x = __shfl_sync(0xFFFFFFFF, p(0), i);
int y = __shfl_sync(0xFFFFFFFF, p(1), i);
uint32_t b = __ballot_sync(0xFFFFFFFF, p(0) == x && p(1) == y);
if (i == threadIdx.x & 31) result = b;
}
return result;
}
__device__ uint32_t subgroupPartitionedAddNV(float value, uint32_t ballot)
{
float result = 0;
for ( unsigned int i = 0; i < 32; ++i)
{
float other_value = __shfl_sync(0xFFFFFFFF, value, i);
if ((1U << i) & ballot) result += other_value;
}
return result;
}
Thanks to the hint of Abator I came up with a more efficient solution. It's a little ugly because labeled_partition is only implemented for int but works quite well.
template <int GROUP_SIZE = 32>
__device__ cooperative_groups::coalesced_group subgroupPartitionNV(ivec2 p)
{
using namespace cooperative_groups;
thread_block block = this_thread_block();
thread_block_tile<GROUP_SIZE> tile32 = tiled_partition<GROUP_SIZE>(block);
coalesced_group g1 = labeled_partition(tile32, p(0));
coalesced_group g2 = labeled_partition(tile32, p(1));
details::_coalesced_group_data_access acc;
return acc.construct_from_mask<coalesced_group>(acc.get_mask(g1) & acc.get_mask(g2));
}
template <typename T, int GROUP_SIZE = 32>
__device__ T subgroupPartitionedAddNV(T value, cooperative_groups::coalesced_group group)
{
int s = group.size();
int r = group.thread_rank();
for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2)
{
auto v = group.template shfl_down(value, offset);
if (r + offset < s) value += v;
}
return value;
}

How to create integer function with variable that doesn't reset each increment

I am trying to create a mini football game that gives each player a certain amount of yards every time I press ENTER. I think the problem I am having is that I can't think of a way to to make a variable to add the yards together from each turn. When the first function does initialize I get a stack overflow recurse error. I also can't get the first function to initialize. I don't know if that is connected.
Here is what I have so far
package Football;
import java.util.Scanner;
import java.util.Random;
public class FootballGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int l = 0;
int m = 0;
Scanner in = new Scanner(System.in);
System.out.println(" THIS IS VIRTUAL FOOTBALL!");
System.out.println("In order to to take your turn and gain yards all you have to do is press ENTER");
System.out.println("First type your names");
System.out.println("player 1?");
String player1 = in.nextLine();
System.out.println("player 2?");
String player2 = in.nextLine();
System.out.println("OK! Lets play.");
in.next();
l = firstPlayer(player1, player2, l);
}
public static int firstPlayer(String player1, String player2, int l)
{
for(int i = 0; i >= 100; i++ )
{
Random r = new Random();
int rv = 0;
int y = r.nextInt(21);
l = (y + l);
System.out.println(player1 + " gained " + y + " yards for a total of " + l + " yards");
if(rv < 100)
{
secondPlayer(player1, player2, l);
}
if (l >= 100)
{
System.out.println("TOUCHDOWN!");
System.out.println("praise the lord almighty Jesus Jehova, God up above.");
break;
}
}
return l;
}
public static int secondPlayer(String player1, String player2, int m)
{
for(int i = 0; i >= 100; i++)
{
Random r = new Random();
int rv = 0;
int y = r.nextInt(21);
m = (y + m);
System.out.println(player2 + " gained " + y + " yards for a total of" + m + " yards");
if(m < 100)
{
firstPlayer(player1, player2, m);
}
if (m >= 100)
{
System.out.println("TOUCHDOWN!");
System.out.println(player2 + " cheated and won the game");
break;
}
}
return m;
}
}
Any help would be much appreciated.

Reverse engineering history pattern length in branch predictor

I'm trying to find the length of the history pattern in the branch predictor of my computer's processor. I generated variable length array of bits and have if conditions based on the value of the bit. I will then plot the run time of different execution of the function and search for the knee in the graph. but I don't see any such point in the graph. What am I doing wrong? Any idea?
Here is my code:
vector<int> randomArr(int n)
{
vector<int> arr (n);
for ( int i=0; i <n; i++){
arr[i] = rand() % 2;
}
return arr;
}
int branchy(vector<int> & arr){
int a = 0 ;
int b = 0 ;
for ( int i = 0 ; i < arr.size() ; i++ ) {
if ( arr[i] == 0)
a++;
else
b++;
}
return a^b;
}
int main() {
long int iterations = 100000;
int start_s;
int stop_s;
ofstream runtimesFile;
runtimesFile.open("runtimesFile.txt");
for (int j=0; j <iterations ; j++){
vector<int> arr = randomArr(j);
start_s=clock();
branchy(arr);
stop_s=clock();
runtimesFile<< to_string(stop_s-start_s)<<"\n";
}
runtimesFile.close();
return 0;
}

How to simplify this loop?

Considering an array a[i], i=0,1,...,g, where g could be any given number, and a[0]=1.
for a[1]=a[0]+1 to 1 do
for a[2]=a[1]+1 to 3 do
for a[3]=a[2]+1 to 5 do
...
for a[g]=a[g-1]+1 to 2g-1 do
#print a[1],a[2],...a[g]#
The problem is that everytime we change the value of g, we need to modify the code, those loops above. This is not a good code.
Recursion is one way to solve this(although I was love to see an iterative solution).
!!! Warning, untested code below !!!
template<typename A, unsigned int Size>
void recurse(A (&arr)[Size],int level, int g)
{
if (level > g)
{
// I am at the bottom level, do stuff here
return;
}
for (arr[level] = arr[level-1]+1; arr[level] < 2 * level -1; arr[level]++)
{
recurse(copy,level+1,g);
}
}
Then call with recurse(arr,1,g);
Imagine you are representing numbers with an array of digits. For example, 682 would be [6,8,2].
If you wanted to count from 0 to 999 you could write:
for (int n[0] = 0; n[0] <= 9; ++n[0])
for (int n[1] = 0; n[1] <= 9; ++n[1])
for (int n[2] = 0; n[2] <= 9; ++n[2])
// Do something with three digit number n here
But when you want to count to 9999 you need an extra for loop.
Instead, you use the procedure for adding 1 to a number: increment the final digit, if it overflows move to the preceding digit and so on. Your loop is complete when the first digit overflows. This handles numbers with any number of digits.
You need an analogous procedure to "add 1" to your loop variables.
Increment the final "digit", that is a[g]. If it overflows (i.e. exceeds 2g-1) then move on to the next most-significant "digit" (a[g-1]) and repeat. A slight complication compared to doing this with numbers is that having gone back through the array as values overflow, you then need to go forward to reset the overflowed digits to their new base values (which depend on the values to the left).
The following C# code implements both methods and prints the arrays to the console.
static void Print(int[] a, int n, ref int count)
{
++count;
Console.Write("{0} ", count);
for (int i = 0; i <= n; ++i)
{
Console.Write("{0} ", a[i]);
}
Console.WriteLine();
}
private static void InitialiseRight(int[] a, int startIndex, int g)
{
for (int i = startIndex; i <= g; ++i)
a[i] = a[i - 1] + 1;
}
static void Main(string[] args)
{
const int g = 5;
// Old method
int count = 0;
int[] a = new int[g + 1];
a[0] = 1;
for (a[1] = a[0] + 1; a[1] <= 2; ++a[1])
for (a[2] = a[1] + 1; a[2] <= 3; ++a[2])
for (a[3] = a[2] + 1; a[3] <= 5; ++a[3])
for (a[4] = a[3] + 1; a[4] <= 7; ++a[4])
for (a[5] = a[4] + 1; a[5] <= 9; ++a[5])
Print(a, g, ref count);
Console.WriteLine();
count = 0;
// New method
// Initialise array
a[0] = 1;
InitialiseRight(a, 1, g);
int index = g;
// Loop until all "digits" have overflowed
while (index != 0)
{
// Do processing here
Print(a, g, ref count);
// "Add one" to array
index = g;
bool carry = true;
while ((index > 0) && carry)
{
carry = false;
++a[index];
if (a[index] > 2 * index - 1)
{
--index;
carry = true;
}
}
// Re-initialise digits that overflowed.
if (index != g)
InitialiseRight(a, index + 1, g);
}
}
I'd say you don't want nested loops in the first place. Instead, you just want to call a suitable function, taking the current nesting level, the maximum nesting level (i.e. g), the start of the loop, and whatever if needs as context for the computation as arguments:
void process(int level, int g, int start, T& context) {
if (level != g) {
for (int a(start + 1), end(2 * level - 1); a < end; ++a) {
process(level + 1, g, a, context);
}
}
else {
computation goes here
}
}