Divide function - binary

I need to write the divide function in the Jack language.
my code is:
function int divide(int x, int y) {
var int result;
var boolean neg;
let neg = false;
if(((x>0) & (y<0)) | ((x<0) & (y>0))){
let neg = true;
let x = Math.abs(x);
let y = Math.abs(y);
}
if (y>x){
return 0;
}
let result = Math.divide(x, y+y);
if ((x-(2*result*y)) < y) {
if (neg){
return -(result + result);
} else {
return (result + result);
}
} else {
if (neg){
return -(result + result + 1);
} else {
return (result + result + 1);
}
}
}
this algorithm is sub-optimal since each multiplication operation also requires O(n) addition and subtraction operations.
Can I compute the product 2*result*y without any multiplication?
Thanks

Here's an implementation of (unsigned) restoring division (x/y), I don't actually know Jack though so I'm not 100% sure about this
var int r;
let r = 0;
var int i;
let i = 0;
while (i < 16)
{
let r = r + r;
if ((x & 0x8000) = 0x8000) {
let r = r + 1;
}
if ((y ^ 0x8000) > (r ^ 0x8000)) { // this is an unsigned comparison
let x = x + x;
}
else {
let r = r - y;
let x = x + x + 1;
}
let i = i + 1;
}
return x;
You should be able to turn that into signed division.

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.

I am having problems with my FFT in c#

Does Microsoft have a good FFT that I can use ?
so I made my owe FFT and it work from some case but now all...
like if I get it
f(t) =10*sin(2*pi *3000*t) + 20*sin(1000* 2* PI* t)
it will work but if I add
+ 5*sin(2*pi*100*T) is start acting fun?
now in Matlab it works good but not in my close, also my fft only seem to return the right numbers in the Image not so much in the real...
here is my code:
enter code here
public struct polar1
{
public double real;
public double img;
};
private float Fs;
private int N;
private polar1 [] F;
private int R;
public DSPclass(float[] DSP1,int f1)
{
N = DSP1.Length;
R = DSP1.Length;
F = new polar1[N];
Fs = (float)f1;
}
public void FFT1(float[] DSP1)
{
polar1[] x = new polar1[DSP1.Length];
for (int v = 0; v < N; v++)
{
x[v].real = DSP1[v];
x[v].img = 0;
}
F = FFT(x);
int temp;
}
public polar1[] FFT(polar1[] x)
{
int N2 = x.Length;
polar1[] X = new polar1[N2];
if (N2 == 1)
{
return x;
}
polar1[] odd = new polar1[N2 / 2];
polar1[] even = new polar1[N2 / 2];
polar1[] Y_Odd = new polar1[N2 / 2];
polar1[] Y_Even = new polar1[N2 / 2];
for (int t = 0; t < N2 / 2; t++)
{
even[t].img = x[t * 2].img;
even[t].real = x[t * 2].real;
odd[t].img = x[(t * 2) + 1].img;
odd[t].real = x[(t * 2) + 1].real;
}
Y_Even = FFT(even);
Y_Odd = FFT(odd);
polar1 temp4;
for (int k = 0; k < (N2 / 2); k++)
{
temp4 = Complex1(k, N2);
X[k].real = Y_Even[k].real + (Y_Odd[k].real * temp4.real);
X[k + (N2 / 2)].real = Y_Even[k].real - (Y_Odd[k].real * temp4.real);
X[k].img = Y_Even[k].img + (Y_Odd[k].real * temp4.img);
X[k + (N2 / 2)].img = Y_Even[k].img - (Y_Odd[k].real * temp4.img);
}
return X;
}
public double magnitude( polar1 temp)
{
double tempD;
tempD = Math.Sqrt ( (temp.img * temp.img) + (temp.real * temp.real));
return tempD;
}
public polar1 Complex2(int K, int N, int F3)
{
polar1 temp;
double temp1;
temp1 = (2D * K *F3) / N;
if (temp1 % 2 == 0 || temp1 == 0)
{
temp.real = 1D;
temp.img = 0D;
}
else if ((temp1 - 1) % 2 == 0)
{
temp.real = -1D;
temp.img = 0D;
}
else if ((temp1 / .5D) - 1 % 2 == 0)
{
if ((temp1 - .5D) % 2 == 0)
{
temp.real = 0D;
temp.img = -1D;
}
else
{
temp.real = 0D;
temp.img = 1D;
}
}
else
{
temp.real = Math.Cos(temp1 * Math.PI);
temp.img = -1D * Math.Sin(temp1 * Math.PI);
}
return temp;
}
public polar1 Complex1(int K, int N3)
{
polar1 temp;
double temp1;
temp1 = (2D * Math.PI *K) / N3;
temp.real = Math.Cos(temp1);
temp.img = Math.Sin(temp1);
return temp;
}
public int Apm(double[] img, double[] real)
{
for (int i = 0; i < R; i++)
{
img[i] = F[i].img;
real[i] = F[i].real;
}
return R;
}
public int frequencies(float [] freq, float [] Ctemp)
{
bool flag = false;
bool flagD = false;
float tempOld = 0;
float tempNew =0;
int tempc = 0;
int counter = 0;
for (int i = 0; i < R; i++)
{
if (((i / N) * Fs) >= (Fs / 2))
{
return counter;
}
if ((int)F[i].img != 0 )
{
flag = true;
tempOld = (float)(Math.Abs(F[i].img));
}
else
{
if (flagD == true)
{
freq[counter] = ((float)tempc / (float)N) * Fs;
Ctemp[counter] = tempNew; //magnitude(F[tempc]);
counter++;
flagD = false;
}
flag = false;
tempOld = 0;
tempNew = 0;
}
if(flag == true)
{
if (tempOld > tempNew)
{
tempNew = tempOld;
tempc = i;
flagD = true;
}
}
}
return counter;
}
}

An error with dec to bin

I have been debugging this function but I don't know why is it throwing 99 when I send 4 to the function.
This is a function to covert from decimal to binary.
Actually, I have tried to cout exp, res and the other variables in each step and then multiply them but I don't know. It doesn't make sense.
int DecToBinary(long num) {
if(num == 0) {
return 0;
}
else if(num == 1) {
return 1;
}
int exp = 0;
int res = 0;
for (; num != 0; exp++){
res = res+num%2*pow(10,exp);
num = num/2;
}
return res;
}
Thank you guys.
if(num == 0) {
return 0;
}
else if(num == 0) {
return 1;
}
You know the second branch will never be executed, right?
Furthermore:
pow(10,exp);
this yields a floating-point number. Be prepared for rounding errors. Even better: don't use pow() at all (you don't need floating-point numbers for working with integers). Simply do the division step by step, accumulating the result in a variable.
int dec2bin(int n)
{
int r = 0, tp = 1;
while (n) {
r += (n % 2) * tp;
n >>= 1;
tp *= 10;
}
return r;
}