I'm making a program that generates the "names" (random lines of text from the ASCII) that are the names of movies in this instance. I should follow them up with a "name" of a director for each (can also be generated from the ASCII), and after that the random year that is the year the "movie" was made (from 1896 to 2021).
I have two separate functions that randomize the names of the movies and directors, but I'm confused with the supposed placement of the Console.Writeline which the intelligence only allows inside their own loops. Otherwise it doesn't seem to be able to use the values "directorname" and "moviename".
I need it to write the names in a single line, ai. (KHGTJ, KGHTJF).
Also I need a way to generate a random year from 1896 to 2021 that is printed after the names of the movie, and director, ai. (KFJU, MDDOS, 1922).
private static void GenerateRandomNames()
{
Random random = new Random();
char y = (char)65;
for (int p = 0; p < 100; p++)
{
string directorname = "";
for (int m = 0; m < 5; m++)
{
int b = random.Next(65, 90);
y = (char)b;
directorname += y;
}
Console.WriteLine(directorname);
}
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
Console.WriteLine(moviename);
}
Console.WriteLine();
I need to fix the plecement of the Console.Writeline() so it can print both names in the same line, and be able to print the year after them.
I've tried placing the Console.Writeline() outside the loops, but of course it can't then use the name. But this way it prints them the wrong way.
If you want to have minimal changes in your code, you can use the following code:
private static void GenerateRandomNames()
{
//a separate thing for the names of the directors (ASCII)
// then for the years they were made (1896-2021)
//they should all be printed in the end ie. (KGMFK, JDBDJ, 1922)
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string directors = "";
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
directors += x;
}
Console.WriteLine("( "+directors +", "+ moviename + ", " +rnd.Next(1896, 2021).ToString()+" )");
}
Console.WriteLine();
}
and result:
Not sure if it is good to answer this type of question, but answering it anyway.
Since you only want other 5-letter words and 4-digit numbers ranging from 1896 - 2021,
Just get another variable 'b' and do the same as you did for 'a', like :
int b = rnd.Next(65,90) ;
y = char(b) ;
director name += y ;
and to get the year value, you can use this :
year = rnd.Next(1896,2021)
So, by combining all of the above, you have the code like this :
internal class Program
{
private static void GenerateRandomNames()
{
Random rnd = new Random();
char x = (char)65;
char y = (char) 65 ;
for (int j = 0; j < 100; j++)
{
string moviename = "";
string directorName = "";
int year = rnd.Next(1896,2021);
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
int b = rnd.Next(65, 90);
x = (char)a;
moviename += x;
y = (char)a;
directorName += x;
}
Console.WriteLine(moviename);
Console.WriteLine(directorName);
Console.WriteLine(year);
}
Console.WriteLine();
}
static void Main(string[] args)
{
GenerateRandomNames();
}
}
The task becomes easier if you extract the creation of a random name to a new method. This allows you to call it twice easily. I moved the random object to the class (making it a class field), so that it can be reused in different places.
internal class Program
{
private static readonly Random _rnd = new Random();
private static string CreateRandomName(int minLength, int maxLength)
{
string name = "";
for (int i = 0; i < _rnd.Next(minLength, maxLength + 1); i++)
{
char c = (char)_rnd.Next((int)'A', (int)'Z' + 1);
name += c;
}
return name;
}
private static void WriteRandomNames()
{
for (int i = 0; i < 100; i++)
{
string movie = CreateRandomName(4, 40);
string director = CreateRandomName(3, 30);
int year = _rnd.Next(1896, 2022);
Console.WriteLine($"{movie}, {director}, {year}");
}
Console.WriteLine();
}
static void Main(string[] args)
{
WriteRandomNames();
}
}
Note that the second parameter of the Next(Int32, Int32) method is the exclusive upper bound. Therefore I added 1.
output:
HATRHKYAHQTGS, NCPQ, 1999
QVJAYOTTISN, LJTGJDMB, 2018
JEXJDICLRMZFRV, GJPZHFBHOTR, 1932
SKFINIGVYUIIVBD, DIZSKOS, 1958
LWWGSEIZT, AMDW, 1950
OAVZVQVFPPBY, SPEZZE, 2008
YLNTZZIXOCNENGYUL, URNJMK, 1962
ONIN, WUITIL, 1987
RJUXGORWDVQRILDWWKSDWF, MOEYPZQPV, 1946
YUQSSOPZTCTRM, UEPPXIVGERG, 1994
KILWEYC, QJZOTLKFMVPHUE, 1915
Wow, in the time it took me to write an answer, three or more others appeared. They all seem like pretty good answers to me, but since I went to the trouble of writing this code, here you go. :)
I focused on using the same Random in different ways, because I think that's what you were asking about.
using System;
using System.Collections.Generic;
using System.Linq;
Random rnd = new Random(1950);
GenerateRandomNames();
void GenerateRandomNames()
{
for (int j = 0; j < 100; j++)
{
// here's one way to get a random string
string name = Guid.NewGuid().ToString().Substring(0, 5);
string description = new string(GetRandomCharacters(rnd.Next(5,16)).ToArray());
string cleaner = new string(GetCleanerCharacters(rnd.Next(5, 16)).ToArray());
string preferred = new string(GetPreferredRandomCharacters(rnd.Next(5, 16)).ToArray());
int year = rnd.Next(1896, DateTime.Now.Year + 1);
Console.WriteLine($"{year}\t{preferred}");
Console.WriteLine($"{year}\t{cleaner}");
Console.WriteLine($"{year}\t{name}\t{description}");
Console.WriteLine();
}
Console.WriteLine();
}
// Not readable
IEnumerable<char> GetRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
yield return Convert.ToChar(rnd.Next(0, 255));
}
}
// gives you lots of spaces
IEnumerable<char> GetCleanerCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
char c = Convert.ToChar(rnd.Next(0, 255));
if (char.IsLetter(c))
{
yield return c;
}
else
{
yield return ' ';
}
}
}
// Most readable (in my opinion), but still nonsense.
IEnumerable<char> GetPreferredRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
bool randomSpace = rnd.Next(0, 6) == 3;
if (i > 0 && randomSpace) // prevent it from starting with a space
{
yield return ' ';
continue;
}
var c = Convert.ToChar(rnd.Next(65, 91)); // uppercase letters
if (rnd.Next(0, 2) == 1)
{
c = char.ToLower(c);
}
yield return c;
}
}
In the inputs first row, there are two numbers the first one is the amount of rows N and the second one is a limit K. I have to find the first and last element's indexes of the longest continuous subarray which's elements are greater than K.
(There are lots of inputs with different numbers, but they have the same base.)
The example input is:
7 20
18
23
44
32
9
30
26
So the N is 7 and K is 20, in this case there are 2 continuous subarrays which would be correct: [23, 44, 32] and [30, 26], but I only need the longer ones indexes.
Therefore the output is:
1 3
I have split the first row, so i have the N and K, I have added the remaining rows in an array H[ ]. Now I just have to find the longest continuous subarray and get the first and last element's indexes.
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
}
}
And I'm stuck here, if someone could help me I would greatly appreciate their assistance.
Sounds like homework, but an interesting challenge none the less. Here's one way of doing it.
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
}
int greatesRangeStartIndex = -1;
int greatestRangeEndIndex = -1;
int greatestIndexSpan = 0;
for (int i = 0; i < N; i++)
{
// Find the first array item that meets the criteria.
if (H[i] > K)
{
var rangeStartIndex = i;
// Continue spinning through the array while we still meet the criteria.
do
{
i++;
} while (i < N && H[i] > K);
var rangeEndIndex = i - 1;
// Determine the width of our current range and check if its our largest one.
// If the range is the biggest so far, store that as the current largest range.
var indexSpan = rangeEndIndex - rangeStartIndex + 1;
if (indexSpan > greatestIndexSpan)
{
greatesRangeStartIndex = rangeStartIndex;
greatestRangeEndIndex = rangeEndIndex;
greatestIndexSpan = indexSpan;
}
}
}
// Report out the results.
// Not part of the requirements, but will remove false reporting of the criteria being in index position 1.
if (greatesRangeStartIndex == -1 && greatestRangeEndIndex == -1)
{
Console.WriteLine($"No values in the array were greater than {K}.");
}
else
{
Console.WriteLine($"{greatesRangeStartIndex} {greatestRangeEndIndex}");
}
}
You could do something like this (could be improved a lot with LINQ, but i suppose this is an introduction exercise of some sorts, so i'll stick to this):
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
int firstIndex = 0;
int lastIndex = 0;
int subarraySize = 0;
int firstIndexTemp = 0;
int lastIndexTemp = 0;
int subarraySizeTemp = 0;
bool arrayContinues = false;
for (int i = 0; i < N; i++)
{
//Read the newest index
H[i] = int.Parse(Console.ReadLine());
/*If arrrayContinues is true, and the current value is higher than the threshold K,
this means this is the continuation of a subarray. For now, the current value is the last index value
*/
if (H[i] > K && arrayContinues)
{
subarraySizeTemp++;
lastIndexTemp = i;
}
/*If arrrayContinues is false, but the current value is higher than the threshold K,
this means this is the first index of a new subarray
*/
else if (H[i] > K)
{
subarraySizeTemp = 1;
firstIndexTemp = i;
arrayContinues = true;
}
/*If we reach this statement, the current value is smaller than K,
* so the array streak stopped (or was already stopped by a previous smaller value)
*/
else
{
arrayContinues = false;
}
/* We're only interested in the largest subarray,
* so let's override the previous largest array only when the current one is larger.
*/
if(subarraySizeTemp > subarraySize)
{
subarraySize = subarraySizeTemp;
firstIndex = firstIndexTemp;
lastIndex = lastIndexTemp;
}
}
/*Let's print our result!*/
Console.WriteLine($"{firstIndex} {lastIndex}");
}
Other answers work out but you can use something simpler like this;
private static void Main()
{
var input = Console.ReadLine().Split(' ');
var n = int.Parse(input[0]);
var k = int.Parse(input[1]);
var startingIndex = 0;
var endingIndex = 0;
var temporaryIndex = 0;
var items = new int[n];
for (var i = 0; i < n; i++)
{
var value = int.Parse(Console.ReadLine());
items[i] = value;
if (value < k)
{
temporaryIndex = i;
continue;
}
var currentSize = i - temporaryIndex;
var currentBiggestSize = endingIndex - startingIndex;
if (currentSize > currentBiggestSize)
{
startingIndex = temporaryIndex + 1;
endingIndex = i;
}
}
Console.WriteLine($"Biggest Subset's Start and Ending Indexes: {startingIndex} {endingIndex}");
Console.ReadLine();
}
Another Option:
static void Main(string[] args)
{
Example(new string[] { "7","20"},new string[] { "18", "23", "44", "32", "9", "30", "26"});
}
static void Example(string[] arr,string[] values)
{
int N = int.Parse(arr[0]);
int K = int.Parse(arr[1]);
int counter = 0;
int most_succesfull_index_yet = 0;
int most_succesfull_length_yet = 0;
for (int i = 1; i < N; i++)
{
if (int.Parse(values[i]) > K)
{
counter++;
}
else
{
if (counter > most_succesfull_length_yet)
{
most_succesfull_length_yet = counter;
most_succesfull_index_yet = i - counter;
}
counter = 0;
}
}
// For last index
if (counter > most_succesfull_length_yet)
{
most_succesfull_length_yet = counter;
most_succesfull_index_yet = N - counter;
}
var bestStart = most_succesfull_index_yet;
var bestEnd = most_succesfull_index_yet + most_succesfull_length_yet -1;
Console.WriteLine(bestStart + "," + bestEnd);
Console.ReadLine();
}
Another solution, keeping indexes of the longest match, and displaying the max length, indexes, and rows values at the end.
static void Main(string[] args)
{
var data = #"7 20
18
23
44
32
9
30
26";
var rows = data.Split("\r\n");
var frow = rows[0].Split(" ");
int N = int.Parse(frow[0]);
int K = int.Parse(frow[1]);
int max = 0, currentmax = 0;
int i = 1;
int[] indexes = null;
while(i < rows.Length)
{
if (int.Parse(rows[i]) > K)
{
currentmax++;
}
else
{
if (currentmax > max)
{
max = currentmax;
indexes = new int[max];
indexes[--currentmax] = i;
do
{
indexes[--currentmax] = indexes[currentmax + 1] - 1;
} while (currentmax > 0);
currentmax = 0;
}
}
i++;
}
if (indexes != null) {
Console.WriteLine($"{max} occured on indexes {string.Join(",", indexes)} with values {string.Join(",", indexes.Select(i => rows[i]).ToList())}");
}
}
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
bool isChain = false;
int currentFirstIndex = -1;
int maxFirstIndex = -1;
int currentLastIndex = -1;
int maxLastIndex = -1;
int currentLength = 0;
int maxLength = 0;
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
if(H[i] > K)
{
if (isChain)
{
currentLastIndex = i;
}
else
{
currentFirstIndex = i;
isChain = true;
}
currentLength++;
}
else
{
if (maxLength < currentLength)
{
maxLength = currentLength;
maxFirstIndex = currentFirstIndex;
maxLastIndex = currentLastIndex;
}
currentLength = 0;
isChain = false;
}
}
Console.WriteLine("first: " + maxFirstIndex + " last: " + maxLastIndex);
This could be one of the way
static void Main(string[] args)
{
var firstLineInput = Console.ReadLine().Split(" ");
var numberOfInput = Int64.Parse(firstLineInput[0]);
var value = Int64.Parse(firstLineInput[1]);
var startIndex = -1; //No value greater than value
var endIndex = -1;
var maxLength = 0;
var maxStartIndex = -1;
var maxEndIndex = -1;
for (int i = 0; i < numberOfInput ; i++)
{
var input = Int64.Parse(Console.ReadLine());
if (input > value && startIndex == -1)
{
startIndex = i;
endIndex = i;
if(maxLength == 0)
{
maxLength = 1;
maxStartIndex = startIndex;
maxEndIndex = endIndex;
}
}
else if(input > value && startIndex != -1)
{
endIndex = i;
}
else if(input < value)
{
startIndex = -1;
endIndex = -1;
}
if (maxLength < (endIndex - startIndex))
{
maxLength = endIndex - startIndex;
maxStartIndex = startIndex;
maxEndIndex = endIndex;
}
}
Console.WriteLine($"{maxStartIndex} {maxEndIndex}");
}
What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
(via Introduction to Programming in Java)
Use recursion.
Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call.
The base case is when the input is an empty string the only permutation is the empty string.
Here is my solution that is based on the idea of the book "Cracking the Coding Interview" (P54):
/**
* List permutations of a string.
*
* #param s the input string
* #return the list of permutations
*/
public static ArrayList<String> permutation(String s) {
// The result
ArrayList<String> res = new ArrayList<String>();
// If input string's length is 1, return {s}
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
// Find out the last character
String last = s.substring(lastIndex);
// Rest of the string
String rest = s.substring(0, lastIndex);
// Perform permutation on the rest string and
// merge with the last character
res = merge(permutation(rest), last);
}
return res;
}
/**
* #param list a result of permutation, e.g. {"ab", "ba"}
* #param c the last character
* #return a merged new list, e.g. {"cab", "acb" ... }
*/
public static ArrayList<String> merge(ArrayList<String> list, String c) {
ArrayList<String> res = new ArrayList<>();
// Loop through all the string in the list
for (String s : list) {
// For each string, insert the last character to all possible positions
// and add them to the new list
for (int i = 0; i <= s.length(); ++i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}
Running output of string "abcd":
Step 1: Merge [a] and b:
[ba, ab]
Step 2: Merge [ba, ab] and c:
[cba, bca, bac, cab, acb, abc]
Step 3: Merge [cba, bca, bac, cab, acb, abc] and d:
[dcba, cdba, cbda, cbad, dbca, bdca, bcda, bcad, dbac, bdac, badc, bacd, dcab, cdab, cadb, cabd, dacb, adcb, acdb, acbd, dabc, adbc, abdc, abcd]
Of all the solutions given here and in other forums, I liked Mark Byers the most. That description actually made me think and code it myself.
Too bad I cannot voteup his solution as I am newbie.
Anyways here is my implementation of his description
public class PermTest {
public static void main(String[] args) throws Exception {
String str = "abcdef";
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,0);
}
private static void doPerm(StringBuffer str, int index){
if(index == str.length())
System.out.println(str);
else { //recursively solve this by placing all other chars at current first pos
doPerm(str, index+1);
for (int i = index+1; i < str.length(); i++) {//start swapping all other chars with current first char
swap(str,index, i);
doPerm(str, index+1);
swap(str,i, index);//restore back my string buffer
}
}
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
}
I prefer this solution ahead of the first one in this thread because this solution uses StringBuffer. I wouldn't say my solution doesn't create any temporary string (it actually does in system.out.println where the toString() of StringBuffer is called). But I just feel this is better than the first solution where too many string literals are created. May be some performance guy out there can evalute this in terms of 'memory' (for 'time' it already lags due to that extra 'swap')
A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :
public static Set<String> generatePerm(String input)
{
Set<String> set = new HashSet<String>();
if (input == "")
return set;
Character a = input.charAt(0);
if (input.length() > 1)
{
input = input.substring(1);
Set<String> permSet = generatePerm(input);
for (String x : permSet)
{
for (int i = 0; i <= x.length(); i++)
{
set.add(x.substring(0, i) + a + x.substring(i));
}
}
}
else
{
set.add(a + "");
}
return set;
}
All the previous contributors have done a great job explaining and providing the code. I thought I should share this approach too because it might help someone too. The solution is based on (heaps' algorithm )
Couple of things:
Notice the last item which is depicted in the excel is just for helping you better visualize the logic. So, the actual values in the last column would be 2,1,0 (if we were to run the code because we are dealing with arrays and arrays start with 0).
The swapping algorithm happens based on even or odd values of current position. It's very self explanatory if you look at where the swap method is getting called.You can see what's going on.
Here is what happens:
public static void main(String[] args) {
String ourword = "abc";
String[] ourArray = ourword.split("");
permute(ourArray, ourArray.length);
}
private static void swap(String[] ourarray, int right, int left) {
String temp = ourarray[right];
ourarray[right] = ourarray[left];
ourarray[left] = temp;
}
public static void permute(String[] ourArray, int currentPosition) {
if (currentPosition == 1) {
System.out.println(Arrays.toString(ourArray));
} else {
for (int i = 0; i < currentPosition; i++) {
// subtract one from the last position (here is where you are
// selecting the the next last item
permute(ourArray, currentPosition - 1);
// if it's odd position
if (currentPosition % 2 == 1) {
swap(ourArray, 0, currentPosition - 1);
} else {
swap(ourArray, i, currentPosition - 1);
}
}
}
}
Let's use input abc as an example.
Start off with just the last element (c) in a set (["c"]), then add the second last element (b) to its front, end and every possible positions in the middle, making it ["bc", "cb"] and then in the same manner it will add the next element from the back (a) to each string in the set making it:
"a" + "bc" = ["abc", "bac", "bca"] and "a" + "cb" = ["acb" ,"cab", "cba"]
Thus entire permutation:
["abc", "bac", "bca","acb" ,"cab", "cba"]
Code:
public class Test
{
static Set<String> permutations;
static Set<String> result = new HashSet<String>();
public static Set<String> permutation(String string) {
permutations = new HashSet<String>();
int n = string.length();
for (int i = n - 1; i >= 0; i--)
{
shuffle(string.charAt(i));
}
return permutations;
}
private static void shuffle(char c) {
if (permutations.size() == 0) {
permutations.add(String.valueOf(c));
} else {
Iterator<String> it = permutations.iterator();
for (int i = 0; i < permutations.size(); i++) {
String temp1;
for (; it.hasNext();) {
temp1 = it.next();
for (int k = 0; k < temp1.length() + 1; k += 1) {
StringBuilder sb = new StringBuilder(temp1);
sb.insert(k, c);
result.add(sb.toString());
}
}
}
permutations = result;
//'result' has to be refreshed so that in next run it doesn't contain stale values.
result = new HashSet<String>();
}
}
public static void main(String[] args) {
Set<String> result = permutation("abc");
System.out.println("\nThere are total of " + result.size() + " permutations:");
Iterator<String> it = result.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
This one is without recursion
public static void permute(String s) {
if(null==s || s.isEmpty()) {
return;
}
// List containing words formed in each iteration
List<String> strings = new LinkedList<String>();
strings.add(String.valueOf(s.charAt(0))); // add the first element to the list
// Temp list that holds the set of strings for
// appending the current character to all position in each word in the original list
List<String> tempList = new LinkedList<String>();
for(int i=1; i< s.length(); i++) {
for(int j=0; j<strings.size(); j++) {
tempList.addAll(merge(s.charAt(i), strings.get(j)));
}
strings.removeAll(strings);
strings.addAll(tempList);
tempList.removeAll(tempList);
}
for(int i=0; i<strings.size(); i++) {
System.out.println(strings.get(i));
}
}
/**
* helper method that appends the given character at each position in the given string
* and returns a set of such modified strings
* - set removes duplicates if any(in case a character is repeated)
*/
private static Set<String> merge(Character c, String s) {
if(s==null || s.isEmpty()) {
return null;
}
int len = s.length();
StringBuilder sb = new StringBuilder();
Set<String> list = new HashSet<String>();
for(int i=0; i<= len; i++) {
sb = new StringBuilder();
sb.append(s.substring(0, i) + c + s.substring(i, len));
list.add(sb.toString());
}
return list;
}
Well here is an elegant, non-recursive, O(n!) solution:
public static StringBuilder[] permutations(String s) {
if (s.length() == 0)
return null;
int length = fact(s.length());
StringBuilder[] sb = new StringBuilder[length];
for (int i = 0; i < length; i++) {
sb[i] = new StringBuilder();
}
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int times = length / (i + 1);
for (int j = 0; j < times; j++) {
for (int k = 0; k < length / times; k++) {
sb[j * length / times + k].insert(k, ch);
}
}
}
return sb;
}
One of the simple solution could be just keep swapping the characters recursively using two pointers.
public static void main(String[] args)
{
String str="abcdefgh";
perm(str);
}
public static void perm(String str)
{ char[] char_arr=str.toCharArray();
helper(char_arr,0);
}
public static void helper(char[] char_arr, int i)
{
if(i==char_arr.length-1)
{
// print the shuffled string
String str="";
for(int j=0; j<char_arr.length; j++)
{
str=str+char_arr[j];
}
System.out.println(str);
}
else
{
for(int j=i; j<char_arr.length; j++)
{
char tmp = char_arr[i];
char_arr[i] = char_arr[j];
char_arr[j] = tmp;
helper(char_arr,i+1);
char tmp1 = char_arr[i];
char_arr[i] = char_arr[j];
char_arr[j] = tmp1;
}
}
}
python implementation
def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )
getPermutation('abcd','')
This is what I did through basic understanding of Permutations and Recursive function calling. Takes a bit of time but it's done independently.
public class LexicographicPermutations {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="abc";
List<String>combinations=new ArrayList<String>();
combinations=permutations(s);
Collections.sort(combinations);
System.out.println(combinations);
}
private static List<String> permutations(String s) {
// TODO Auto-generated method stub
List<String>combinations=new ArrayList<String>();
if(s.length()==1){
combinations.add(s);
}
else{
for(int i=0;i<s.length();i++){
List<String>temp=permutations(s.substring(0, i)+s.substring(i+1));
for (String string : temp) {
combinations.add(s.charAt(i)+string);
}
}
}
return combinations;
}}
which generates Output as [abc, acb, bac, bca, cab, cba].
Basic logic behind it is
For each character, consider it as 1st character & find the combinations of remaining characters. e.g. [abc](Combination of abc)->.
a->[bc](a x Combination of (bc))->{abc,acb}
b->[ac](b x Combination of (ac))->{bac,bca}
c->[ab](c x Combination of (ab))->{cab,cba}
And then recursively calling each [bc],[ac] & [ab] independently.
Use recursion.
when the input is an empty string the only permutation is an empty string.Try for each of the letters in the string by making it as the first letter and then find all the permutations of the remaining letters using a recursive call.
import java.util.ArrayList;
import java.util.List;
class Permutation {
private static List<String> permutation(String prefix, String str) {
List<String> permutations = new ArrayList<>();
int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutations.addAll(permutation(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
}
}
return permutations;
}
public static void main(String[] args) {
List<String> perms = permutation("", "abcd");
String[] array = new String[perms.size()];
for (int i = 0; i < perms.size(); i++) {
array[i] = perms.get(i);
}
int x = array.length;
for (final String anArray : array) {
System.out.println(anArray);
}
}
}
this worked for me..
import java.util.Arrays;
public class StringPermutations{
public static void main(String args[]) {
String inputString = "ABC";
permute(inputString.toCharArray(), 0, inputString.length()-1);
}
public static void permute(char[] ary, int startIndex, int endIndex) {
if(startIndex == endIndex){
System.out.println(String.valueOf(ary));
}else{
for(int i=startIndex;i<=endIndex;i++) {
swap(ary, startIndex, i );
permute(ary, startIndex+1, endIndex);
swap(ary, startIndex, i );
}
}
}
public static void swap(char[] ary, int x, int y) {
char temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
}
Java implementation without recursion
public Set<String> permutate(String s){
Queue<String> permutations = new LinkedList<String>();
Set<String> v = new HashSet<String>();
permutations.add(s);
while(permutations.size()!=0){
String str = permutations.poll();
if(!v.contains(str)){
v.add(str);
for(int i = 0;i<str.length();i++){
String c = String.valueOf(str.charAt(i));
permutations.add(str.substring(i+1) + c + str.substring(0,i));
}
}
}
return v;
}
Let me try to tackle this problem with Kotlin:
fun <T> List<T>.permutations(): List<List<T>> {
//escape case
if (this.isEmpty()) return emptyList()
if (this.size == 1) return listOf(this)
if (this.size == 2) return listOf(listOf(this.first(), this.last()), listOf(this.last(), this.first()))
//recursive case
return this.flatMap { lastItem ->
this.minus(lastItem).permutations().map { it.plus(lastItem) }
}
}
Core concept: Break down long list into smaller list + recursion
Long answer with example list [1, 2, 3, 4]:
Even for a list of 4 it already kinda get's confusing trying to list all the possible permutations in your head, and what we need to do is exactly to avoid that. It is easy for us to understand how to make all permutations of list of size 0, 1, and 2, so all we need to do is break them down to any of those sizes and combine them back up correctly. Imagine a jackpot machine: this algorithm will start spinning from the right to the left, and write down
return empty/list of 1 when list size is 0 or 1
handle when list size is 2 (e.g. [3, 4]), and generate the 2 permutations ([3, 4] & [4, 3])
For each item, mark that as the last in the last, and find all the permutations for the rest of the item in the list. (e.g. put [4] on the table, and throw [1, 2, 3] into permutation again)
Now with all permutation it's children, put itself back to the end of the list (e.g.: [1, 2, 3][,4], [1, 3, 2][,4], [2, 3, 1][, 4], ...)
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class hello {
public static void main(String[] args) throws IOException {
hello h = new hello();
h.printcomp();
}
int fact=1;
public void factrec(int a,int k){
if(a>=k)
{fact=fact*k;
k++;
factrec(a,k);
}
else
{System.out.println("The string will have "+fact+" permutations");
}
}
public void printcomp(){
String str;
int k;
Scanner in = new Scanner(System.in);
System.out.println("enter the string whose permutations has to b found");
str=in.next();
k=str.length();
factrec(k,1);
String[] arr =new String[fact];
char[] array = str.toCharArray();
while(p<fact)
printcomprec(k,array,arr);
// if incase u need array containing all the permutation use this
//for(int d=0;d<fact;d++)
//System.out.println(arr[d]);
}
int y=1;
int p = 0;
int g=1;
int z = 0;
public void printcomprec(int k,char array[],String arr[]){
for (int l = 0; l < k; l++) {
for (int b=0;b<k-1;b++){
for (int i=1; i<k-g; i++) {
char temp;
String stri = "";
temp = array[i];
array[i] = array[i + g];
array[i + g] = temp;
for (int j = 0; j < k; j++)
stri += array[j];
arr[z] = stri;
System.out.println(arr[z] + " " + p++);
z++;
}
}
char temp;
temp=array[0];
array[0]=array[y];
array[y]=temp;
if (y >= k-1)
y=y-(k-1);
else
y++;
}
if (g >= k-1)
g=1;
else
g++;
}
}
/** Returns an array list containing all
* permutations of the characters in s. */
public static ArrayList<String> permute(String s) {
ArrayList<String> perms = new ArrayList<>();
int slen = s.length();
if (slen > 0) {
// Add the first character from s to the perms array list.
perms.add(Character.toString(s.charAt(0)));
// Repeat for all additional characters in s.
for (int i = 1; i < slen; ++i) {
// Get the next character from s.
char c = s.charAt(i);
// For each of the strings currently in perms do the following:
int size = perms.size();
for (int j = 0; j < size; ++j) {
// 1. remove the string
String p = perms.remove(0);
int plen = p.length();
// 2. Add plen + 1 new strings to perms. Each new string
// consists of the removed string with the character c
// inserted into it at a unique location.
for (int k = 0; k <= plen; ++k) {
perms.add(p.substring(0, k) + c + p.substring(k));
}
}
}
}
return perms;
}
Here is a straightforward minimalist recursive solution in Java:
public static ArrayList<String> permutations(String s) {
ArrayList<String> out = new ArrayList<String>();
if (s.length() == 1) {
out.add(s);
return out;
}
char first = s.charAt(0);
String rest = s.substring(1);
for (String permutation : permutations(rest)) {
out.addAll(insertAtAllPositions(first, permutation));
}
return out;
}
public static ArrayList<String> insertAtAllPositions(char ch, String s) {
ArrayList<String> out = new ArrayList<String>();
for (int i = 0; i <= s.length(); ++i) {
String inserted = s.substring(0, i) + ch + s.substring(i);
out.add(inserted);
}
return out;
}
We can use factorial to find how many strings started with particular letter.
Example: take the input abcd. (3!) == 6 strings will start with every letter of abcd.
static public int facts(int x){
int sum = 1;
for (int i = 1; i < x; i++) {
sum *= (i+1);
}
return sum;
}
public static void permutation(String str) {
char[] str2 = str.toCharArray();
int n = str2.length;
int permutation = 0;
if (n == 1) {
System.out.println(str2[0]);
} else if (n == 2) {
System.out.println(str2[0] + "" + str2[1]);
System.out.println(str2[1] + "" + str2[0]);
} else {
for (int i = 0; i < n; i++) {
if (true) {
char[] str3 = str.toCharArray();
char temp = str3[i];
str3[i] = str3[0];
str3[0] = temp;
str2 = str3;
}
for (int j = 1, count = 0; count < facts(n-1); j++, count++) {
if (j != n-1) {
char temp1 = str2[j+1];
str2[j+1] = str2[j];
str2[j] = temp1;
} else {
char temp1 = str2[n-1];
str2[n-1] = str2[1];
str2[1] = temp1;
j = 1;
} // end of else block
permutation++;
System.out.print("permutation " + permutation + " is -> ");
for (int k = 0; k < n; k++) {
System.out.print(str2[k]);
} // end of loop k
System.out.println();
} // end of loop j
} // end of loop i
}
}
//insert each character into an arraylist
static ArrayList al = new ArrayList();
private static void findPermutation (String str){
for (int k = 0; k < str.length(); k++) {
addOneChar(str.charAt(k));
}
}
//insert one char into ArrayList
private static void addOneChar(char ch){
String lastPerStr;
String tempStr;
ArrayList locAl = new ArrayList();
for (int i = 0; i < al.size(); i ++ ){
lastPerStr = al.get(i).toString();
//System.out.println("lastPerStr: " + lastPerStr);
for (int j = 0; j <= lastPerStr.length(); j++) {
tempStr = lastPerStr.substring(0,j) + ch +
lastPerStr.substring(j, lastPerStr.length());
locAl.add(tempStr);
//System.out.println("tempStr: " + tempStr);
}
}
if(al.isEmpty()){
al.add(ch);
} else {
al.clear();
al = locAl;
}
}
private static void printArrayList(ArrayList al){
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
}
//Rotate and create words beginning with all letter possible and push to stack 1
//Read from stack1 and for each word create words with other letters at the next location by rotation and so on
/* eg : man
1. push1 - man, anm, nma
2. pop1 - nma , push2 - nam,nma
pop1 - anm , push2 - amn,anm
pop1 - man , push2 - mna,man
*/
public class StringPermute {
static String str;
static String word;
static int top1 = -1;
static int top2 = -1;
static String[] stringArray1;
static String[] stringArray2;
static int strlength = 0;
public static void main(String[] args) throws IOException {
System.out.println("Enter String : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bfr = new BufferedReader(isr);
str = bfr.readLine();
word = str;
strlength = str.length();
int n = 1;
for (int i = 1; i <= strlength; i++) {
n = n * i;
}
stringArray1 = new String[n];
stringArray2 = new String[n];
push(word, 1);
doPermute();
display();
}
public static void push(String word, int x) {
if (x == 1)
stringArray1[++top1] = word;
else
stringArray2[++top2] = word;
}
public static String pop(int x) {
if (x == 1)
return stringArray1[top1--];
else
return stringArray2[top2--];
}
public static void doPermute() {
for (int j = strlength; j >= 2; j--)
popper(j);
}
public static void popper(int length) {
// pop from stack1 , rotate each word n times and push to stack 2
if (top1 > -1) {
while (top1 > -1) {
word = pop(1);
for (int j = 0; j < length; j++) {
rotate(length);
push(word, 2);
}
}
}
// pop from stack2 , rotate each word n times w.r.t position and push to
// stack 1
else {
while (top2 > -1) {
word = pop(2);
for (int j = 0; j < length; j++) {
rotate(length);
push(word, 1);
}
}
}
}
public static void rotate(int position) {
char[] charstring = new char[100];
for (int j = 0; j < word.length(); j++)
charstring[j] = word.charAt(j);
int startpos = strlength - position;
char temp = charstring[startpos];
for (int i = startpos; i < strlength - 1; i++) {
charstring[i] = charstring[i + 1];
}
charstring[strlength - 1] = temp;
word = new String(charstring).trim();
}
public static void display() {
int top;
if (top1 > -1) {
while (top1 > -1)
System.out.println(stringArray1[top1--]);
} else {
while (top2 > -1)
System.out.println(stringArray2[top2--]);
}
}
}
Another simple way is to loop through the string, pick the character that is not used yet and put it to a buffer, continue the loop till the buffer size equals to the string length. I like this back tracking solution better because:
Easy to understand
Easy to avoid duplication
The output is sorted
Here is the java code:
List<String> permute(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
boolean[] used = new boolean[chars.length];
List<String> res = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
Arrays.sort(chars);
helper(chars, used, sb, res);
return res;
}
void helper(char[] chars, boolean[] used, StringBuilder sb, List<String> res) {
if (sb.length() == chars.length) {
res.add(sb.toString());
return;
}
for (int i = 0; i < chars.length; i++) {
// avoid duplicates
if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) {
continue;
}
// pick the character that has not used yet
if (!used[i]) {
used[i] = true;
sb.append(chars[i]);
helper(chars, used, sb, res);
// back tracking
sb.deleteCharAt(sb.length() - 1);
used[i] = false;
}
}
}
Input str: 1231
Output list: {1123, 1132, 1213, 1231, 1312, 1321, 2113, 2131, 2311, 3112, 3121, 3211}
Noticed that the output is sorted, and there is no duplicate result.
Recursion is not necessary, even you can calculate any permutation directly, this solution uses generics to permute any array.
Here is a good information about this algorihtm.
For C# developers here is more useful implementation.
public static void main(String[] args) {
String word = "12345";
Character[] array = ArrayUtils.toObject(word.toCharArray());
long[] factorials = Permutation.getFactorials(array.length + 1);
for (long i = 0; i < factorials[array.length]; i++) {
Character[] permutation = Permutation.<Character>getPermutation(i, array, factorials);
printPermutation(permutation);
}
}
private static void printPermutation(Character[] permutation) {
for (int i = 0; i < permutation.length; i++) {
System.out.print(permutation[i]);
}
System.out.println();
}
This algorithm has O(N) time and space complexity to calculate each permutation.
public class Permutation {
public static <T> T[] getPermutation(long permutationNumber, T[] array, long[] factorials) {
int[] sequence = generateSequence(permutationNumber, array.length - 1, factorials);
T[] permutation = generatePermutation(array, sequence);
return permutation;
}
public static <T> T[] generatePermutation(T[] array, int[] sequence) {
T[] clone = array.clone();
for (int i = 0; i < clone.length - 1; i++) {
swap(clone, i, i + sequence[i]);
}
return clone;
}
private static int[] generateSequence(long permutationNumber, int size, long[] factorials) {
int[] sequence = new int[size];
for (int j = 0; j < sequence.length; j++) {
long factorial = factorials[sequence.length - j];
sequence[j] = (int) (permutationNumber / factorial);
permutationNumber = (int) (permutationNumber % factorial);
}
return sequence;
}
private static <T> void swap(T[] array, int i, int j) {
T t = array[i];
array[i] = array[j];
array[j] = t;
}
public static long[] getFactorials(int length) {
long[] factorials = new long[length];
long factor = 1;
for (int i = 0; i < length; i++) {
factor *= i <= 1 ? 1 : i;
factorials[i] = factor;
}
return factorials;
}
}
My implementation based on Mark Byers's description above:
static Set<String> permutations(String str){
if (str.isEmpty()){
return Collections.singleton(str);
}else{
Set <String> set = new HashSet<>();
for (int i=0; i<str.length(); i++)
for (String s : permutations(str.substring(0, i) + str.substring(i+1)))
set.add(str.charAt(i) + s);
return set;
}
}
Permutation of String:
public static void main(String args[]) {
permu(0,"ABCD");
}
static void permu(int fixed,String s) {
char[] chr=s.toCharArray();
if(fixed==s.length())
System.out.println(s);
for(int i=fixed;i<s.length();i++) {
char c=chr[i];
chr[i]=chr[fixed];
chr[fixed]=c;
permu(fixed+1,new String(chr));
}
}
Here is another simpler method of doing Permutation of a string.
public class Solution4 {
public static void main(String[] args) {
String a = "Protijayi";
per(a, 0);
}
static void per(String a , int start ) {
//bse case;
if(a.length() == start) {System.out.println(a);}
char[] ca = a.toCharArray();
//swap
for (int i = start; i < ca.length; i++) {
char t = ca[i];
ca[i] = ca[start];
ca[start] = t;
per(new String(ca),start+1);
}
}//per
}
A java implementation to print all the permutations of a given string considering duplicate characters and prints only unique characters is as follow:
import java.util.Set;
import java.util.HashSet;
public class PrintAllPermutations2
{
public static void main(String[] args)
{
String str = "AAC";
PrintAllPermutations2 permutation = new PrintAllPermutations2();
Set<String> uniqueStrings = new HashSet<>();
permutation.permute("", str, uniqueStrings);
}
void permute(String prefixString, String s, Set<String> set)
{
int n = s.length();
if(n == 0)
{
if(!set.contains(prefixString))
{
System.out.println(prefixString);
set.add(prefixString);
}
}
else
{
for(int i=0; i<n; i++)
{
permute(prefixString + s.charAt(i), s.substring(0,i) + s.substring(i+1,n), set);
}
}
}
}
String permutaions using Es6
Using reduce() method
const permutations = str => {
if (str.length <= 2)
return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
.split('')
.reduce(
(acc, letter, index) =>
acc.concat(permutations(str.slice(0, index) + str.slice(index + 1)).map(val => letter + val)),
[]
);
};
console.log(permutations('STR'));
In case anyone wants to generate the permutations to do something with them, instead of just printing them via a void method:
static List<int[]> permutations(int n) {
class Perm {
private final List<int[]> permutations = new ArrayList<>();
private void perm(int[] array, int step) {
if (step == 1) permutations.add(array.clone());
else for (int i = 0; i < step; i++) {
perm(array, step - 1);
int j = (step % 2 == 0) ? i : 0;
swap(array, step - 1, j);
}
}
private void swap(int[] array, int i, int j) {
int buffer = array[i];
array[i] = array[j];
array[j] = buffer;
}
}
int[] nVector = new int[n];
for (int i = 0; i < n; i++) nVector [i] = i;
Perm perm = new Perm();
perm.perm(nVector, n);
return perm.permutations;
}
How to convert an integer number into its binary representation?
I'm using this code:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
But it throws an exception:
Could not find any parsable digits
Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.
int value = 8;
string binary = Convert.ToString(value, 2);
Which returns 1000.
Convert from any classic base to any base in C#
string number = "100";
int fromBase = 16;
int toBase = 10;
string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
Supported bases are 2, 8, 10 and 16
Very Simple with no extra code, just input, conversion and output.
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
primitive way:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n / 2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
Another alternative but also inline solution using Enumerable and LINQ is:
int number = 25;
string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.
So you're getting an error because "8" is not a valid digit in base 2.
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
Will show 15 (1111 base 2 = 15 base 10)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
Will show 61440.
static void convertToBinary(int n)
{
Stack<int> stack = new Stack<int>();
stack.Push(n);
// step 1 : Push the element on the stack
while (n > 1)
{
n = n / 2;
stack.Push(n);
}
// step 2 : Pop the element and print the value
foreach(var val in stack)
{
Console.Write(val % 2);
}
}
I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.
public static string ByteConvert (int num)
{
int[] p = new int[8];
string pa = "";
for (int ii = 0; ii<= 7;ii = ii +1)
{
p[7-ii] = num%2;
num = num/2;
}
for (int ii = 0;ii <= 7; ii = ii + 1)
{
pa += p[ii].ToString();
}
return pa;
}
using System;
class Program
{
static void Main(string[] args) {
try {
int i = (int) Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));
} catch(Exception e) {
Console.WriteLine("\n{0}\n", e.Message);
}
}
public static string ToBinary(Int64 Decimal) {
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0) {
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}
This function will convert integer to binary in C#:
public static string ToBinary(int N)
{
int d = N;
int q = -1;
int r = -1;
string binNumber = string.Empty;
while (q != 1)
{
r = d % 2;
q = d / 2;
d = q;
binNumber = r.ToString() + binNumber;
}
binNumber = q.ToString() + binNumber;
return binNumber;
}
class Program
{
static void Main(string[] args)
{
var #decimal = 42;
var binaryVal = ToBinary(#decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 6;
binaryVal = ToBinary(#decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 47;
binaryVal = ToBinary(#decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 99;
binaryVal = ToBinary(#decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
#decimal = 16;
binaryVal = ToBinary(#decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
Console.WriteLine();
#decimal = 11;
binaryVal = Convert.ToString(#decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int #base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % #base;
reverseBinary += remainder;
round = (int)(number / #base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int #base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var #char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(#base, pow) * #char;
}
return val;
}
}
Learning sources:
Everything you need to know about binary
including algorithm to convert decimal to binary
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
BCL provided Convert.ToString(n, 2) is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.
Following custom implementation works for all integers(-ve and +ve).
Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
Above code is my implementation. So, I'm eager to hear any feedback :)
// I use this function
public static string ToBinary(long number)
{
string digit = Convert.ToString(number % 2);
if (number >= 2)
{
long remaining = number / 2;
string remainingString = ToBinary(remaining);
return remainingString + digit;
}
return digit;
}
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}
This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10) returns the string "1010".
I came across this problem in a coding challenge where you have to convert 32 digit decimal to binary and find the possible combination of the substring.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
int numberofinputs = int.Parse(Console.ReadLine());
List<BigInteger> inputdecimal = new List<BigInteger>();
List<string> outputBinary = new List<string>();
for (int i = 0; i < numberofinputs; i++)
{
inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
}
//processing begins
foreach (var n in inputdecimal)
{
string binary = (binaryconveter(n));
subString(binary, binary.Length);
}
foreach (var item in outputBinary)
{
Console.WriteLine(item);
}
string binaryconveter(BigInteger n)
{
int i;
StringBuilder output = new StringBuilder();
for (i = 0; n > 0; i++)
{
output = output.Append(n % 2);
n = n / 2;
}
return output.ToString();
}
void subString(string str, int n)
{
int zeroodds = 0;
int oneodds = 0;
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
string substring = "";
for (int k = i; k <= j; k++)
{
substring = String.Concat(substring, str[k]);
}
var resultofstringanalysis = stringanalysis(substring);
if (resultofstringanalysis.Equals("both are odd"))
{
++zeroodds;
++oneodds;
}
else if (resultofstringanalysis.Equals("zeroes are odd"))
{
++zeroodds;
}
else if (resultofstringanalysis.Equals("ones are odd"))
{
++oneodds;
}
}
}
string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
outputBinary.Add(outputtest);
}
string stringanalysis(string str)
{
int n = str.Length;
int nofZeros = 0;
int nofOnes = 0;
for (int i = 0; i < n; i++)
{
if (str[i] == '0')
{
++nofZeros;
}
if (str[i] == '1')
{
++nofOnes;
}
}
if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
{
return "both are odd";
}
else if (nofZeros != 0 && nofZeros % 2 != 0)
{
return "zeroes are odd";
}
else if (nofOnes != 0 && nofOnes % 2 != 0)
{
return "ones are odd";
}
else
{
return "nothing";
}
}
Console.ReadKey();
}
}
}
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
This was a interesting read i was looking for a quick copy paste.
I knew i had done this before long ago with bitmath differently.
Here was my take on it.
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
You could stick spacing in there with a bit of modulos in the loop.
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;
var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
Just one line for 8 bit
Console.WriteLine(Convert.ToString(n, 2).PadLeft(8, '0'));
where n is the number