You may not understand what I wrote clearly because English is not my first language.
Anyway, here is what I wrote.
public class Exercises7point11 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] binaryNumber = {{0,0,0},{0,0,0},{0,0,0}};
System.out.print("Enter a number between 0 and 511: ");
int decimalNumber = input.nextInt();
int subtractNumber = 256, number = decimalNumber;
for (int row = 0 ; row < 3; row++){
for (int column = 0 ; column < 3; column++) {
if(number >= subtractNumber) {
binaryNumber[row][column] = 1;
number = number - subtractNumber;
}
else {
subtractNumber = subtractNumber / 2;
binaryNumber[row][column] = 0;
}
}
}
// print
for (int row = 0; row < binaryNumber.length; row++){
for (int column = 0; column < binaryNumber[row].length; column++){
if (binaryNumber[row][column] == 1)
System.out.print("T ");
else if (binaryNumber[row][column] == 0)
System.out.print("H ");
if (column == 2)
System.out.print("\n");
}
}
}
Here is the details. Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (heads) and 1 (tails).
Such as,
1 0 0
0 1 0
1 1 0.
There are a total of 512 possibilities, so I can use decimal numbers 0, 1, 2, 3,..., 511 to represent all states of the matrix. Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
My problem is "subtractNumber = subtractNumber / 2; binaryNumber[row][column] = 0;" in the 18 and 19 lines. Even though 'number is greater than or equal to subtractNumber, 18 and 19 lines are read.
I don't know how I can fix it.
Thank you so much!!
The output is a 3x3 matrix, but that doesn't mean you need to use a 2d array.
Here's a simpler approach. We're turning the user's input into a binary string using the toBinaryString method, then translating the binary string into H/T.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
int input = sc.nextInt();
// Turn input to binary string
String binary = Integer.toBinaryString(input);
// Add enough zeros in front so that the string has 9 characters
binary = binary.format("%09d", Integer.parseInt(binary));
// Iterate through binary string one char at a time
for (int i = 1; i < 10; i++) {
if ('0' == binary.charAt(i - 1)) {
System.out.print("H ");
} else {
System.out.print("T ");
}
// New line after 3 letters
if (i % 3 == 0) {
System.out.println();
}
}
}
Example output
12 in binary is 000001100
Enter a number between 0 and 511: 12
H H H
H H T
T H H
Related
i have that needs me to make a function that counts the occurrences of each number in an array [2,5,6,6,8,4,2,5,2] and print it like this
2 -> 3 times
6 -> 2 times and so on
I did it before but it was to count the occurrences of one number not all of them so can anyone help ... Thanks in advance
to update this is the code I used to count the occurrences of one number
int countTwo(List<int> arr, int value) {
int counter = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
counter++;
}
}
return counter;
}
void main() {
List<int> arr = [5, 6, 15, 2, 8, 2, 38, 2];
int x = countTwo(arr, 2);
print(x);
}
You can create a set from list to get unique int.
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
int counter(int number) {
final int counter = data.where((element) => element == number).length; //you can use for loop here too
return counter;
}
for (int i = 0; i < dataSet.length; i++) {
print(
"number ${dataSet.elementAt(i)} -> ${counter(dataSet.elementAt(i))} times");
}
And with your method just do
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
for (int i = 0; i < dataSet.length; i++) {
final checkNUmber = dataSet.elementAt(i);
print("number $checkNUmber-> ${countTwo(data, checkNUmber)} times");
}
Result
number 2 -> 3 times
number 5 -> 2 times
number 6 -> 2 times
number 8 -> 1 times
number 4 -> 1 times
I'd use a map to collect the count:
var count = <int, int>{};
for (var n in data) {
count[n] = (count[n] ?? 0) + 1;
}
After that, you have all the individual elements, and the number of times it occurred:
for (var n in count.keys) {
print("$n: ${count[n]} times");
}
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);
}
}
I'm looking for a tip for a AS3 script, have no idea how to start there
Button, if clicked the function is executed, which outputs a predefined value as the cross sum of a number string.
Example:
Cross sum should be 10
By clicking on the button, the function generates the number 55 or 82 or 37 or 523, ie numbers with the cross sum 10
An alternative way using % (modulo) instead of a string. You could write that into one line like this:
while (sum != 0) { qsum += sum % 10; sum /= 10; }
The trick is that modulo will give us only the last digit of the longer number, then we divide by 10 to trim off that last number (from longer) and we re-read a newer ending digit of the long number.
Example:
Long num = 1234, so each trim gives, 4 then 3 then 2 then 1 and we'll sum them up each time.
usage:
myInt = cross_sum(50); //makes myInt hold answer result of function (where ExpectedValue input is 50).
and the supporting function...
function cross_sum( ExpectedValue: int ) : int
{
var rand :int = Math.floor(Math.random() * 100000000000)
var sum :int = Math.abs( rand );
var qsum :int = 0;
while (sum != 0)
{
qsum += sum % 10; //get last digit of sum...
sum /= 10; //trim down sum by 1 digit...
}
if ( qsum == ExpectedValue ) { return rand; } //# stop here and give back "rand" as answer result.
else { cross_sum( expectedValue ); } //# else if wrong, try again...
}
Got it now.....
the function calculates a number, with the crosssum 50
function berechnen() {
var rand = Math.floor(Math.random() * 100000000000)
var sum = String(rand)
var qsum = 0;
for (var i = 0; i < sum.length; i++) {
qsum += Number(sum.charAt(i));
}
if (qsum == 50) {
summe.text = String(sum);
} else {
berechnen()
}
}
As title describes; I want to add 1 to a 4 bit binary number using only AND OR XOR operations. How can I achieve that?
Regards
Think about what you're doing when you perform addition of decimal numbers in long-hand. It's exactly the same.
Here's how I'd do it, showing a lot of working.
Label the four bits from b0 (least significant bit) to b3 (most significant bit), and introduce 5 carry bits, c0 to c4. The modified values are b3', b2', b1', b0', so your nibble, the carry bits, and the modified values are:
{ b3 b2 b1 b0 }
{ c4 c3 c2 c1 c0 }
{ b3' b2' b1' b0' }
and they are related through:
c0 = 1 (this is to flip the least significant bit)
b0' = XOR(b0, 1)
c1 = AND(b0, 1)
b1' = XOR(b1, c0)
c2 = AND(b1, c0)
b2' = XOR(b2, c1)
c3 = AND(b2, c1)
b3' = XOR(b3, c2)
c4 = AND(b3, c2)
Note:
There's no need for OR to be used.
The choice of four bits is arbitrary - beyond the first bit, the logic is copy/pasta.
When the last carry bit c3 is 0, the number is silently overflowing (going from 15 to 0).
There's no need to have four carry bits, but in keeping with the hand-addition paradigm, I've introduced them anyway.
Four bits is a Nibble.
Sample C# class:
public class Nibble
{
const int bits = 4;
private bool[] _bools = new bool[bits];
public void Reset()
{
for ( int i = 0; i < _bools.Length; i++ )
_bools[i] = false;
}
public void Increment()
{
bool[] result = new bool[bits];
bool[] carries = new bool[bits + 1];
carries[0] = true;
for ( int i = 0; i < bits; i++ )
{
result[i] = _bools[i] ^ carries[i];
carries[i + 1] = _bools[i] && carries[i];
}
if ( carries[bits] )
Console.WriteLine("Overflow!");
_bools = result;
}
public byte Value
{
get
{
byte result = 0;
for ( int i = 0; i < bits; i++ )
{
if ( _bools[i] )
result += (byte)(1 << i);
}
return result;
}
}
}
Usage:
static class Program
{
static void Main()
{
var nibble = new Nibble();
for ( int i = 0; i < 17; i++ )
{
Console.WriteLine(nibble.Value);
nibble.Increment();
}
}
}
Run on Ideone here
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
}
}