For example i've got one array like
int[] array = {1,0,0,1,0}
and one int variable=0;
I want set all array's elements into variable. How can i do this?
variable=10010
In addition if we think about reverse of this situation? Variable's values set to array?
int something=10000 to int[] something={1,0,0,0,0}
Thanks for your all contribution
//==============go forwards===================
int[] array = { 1, 0, 0, 1, 0 };
int variable = 0;
for (int i = 0; i < array.Length; ++i)
{
//first element
if (i == 0)
variable = array[i];
else
{
variable *= 10;
variable += array[i];
}
}
//print resualts
Console.WriteLine(variable);
//===================go backwards===============
int variable2 = 10010;
//convert it into a char array
string value = variable2+"";
//set the array length based on the size
int[] reverse = new int[value.Length];
//loop
for (int i = 0; i < value.Length; ++i)
{
//grab the number from a char value and push it into the array
reverse[i] = (int)Char.GetNumericValue(value[i]);
}
//print out
for(int i = 0; i <reverse.Length;++i)
{
Console.WriteLine("[" + i + "] = " + reverse[i]);
}
Yet another way to do this, but not as compact as others. This approach demonstrates bit-wise operations to construct an int from the array of 0's and 1's.
class Program
{
// converts array of 0's and 1's to an int, and assumes big endian format.
static int bitArrayToInt(int[] bit_array)
{
int rc = 0;
for (int i = 0; i < bit_array.Length; i++)
{
rc <<= 1; // bit shift left
rc |= bit_array[i]; // set LSB according to arr[i].
}
return rc;
}
static void Main(string[] args)
{
int[] array = { 1, 0, 0, 1, 0 };
int rc = bitArrayToInt(array);
System.Console.WriteLine("{0} = {1} binary",rc, Convert.ToString(rc, 2));
System.Console.ReadLine();
}
}
There's a huge number of choices on how to approach the problem.
Shortest quickest method I could think of.
byte[] array = { 1, 0, 1, 0, 0 };
string temp = "";
int result = 0;
for (int i = 0; i < array.Length; i++)
temp += array[i].ToString();
result = Convert.ToInt32(temp);
I'm on my phone here, so bear with me, but if performance isn't an issue then how about something like:
int.Parse(string.Join(string.Empty, array.Select(d => d.ToString()));
Obviously you'll need some error handling around the parsing for overflows, invalid characters, etc.
Related
In my project I've implemented MergeSort, bubble sort, and sequential search algorithms, however the Merge sort is not giving any output to the console, while the others work. I've tried debugging with no real luck.
public static void mergeSort(int[] a)
{
int inputLength = a.Length;
//sets the middle index to the total length divided by 2
int midIndex = a.Length / 2;
//sets the last index to the length minus one (minus one included so
an out of bounds exception is avoided
int endIndex = a.Length - 1;
//left side set to the middle index size
int[] leftArray = new int[midIndex];
//right side set to the total length minus the middle length
int[] rightArray = new int[inputLength - midIndex];
//looping from zero to middle of the array
for (int i = 0; i < midIndex; i++)
{
leftArray[i] = a[i];
}
//looping from the middle to the end of the array
for(int i = midIndex; i < inputLength; i++)
{
rightArray[i - midIndex] = a[i];
}
//recursively called the method to sort these two sides
mergeSort(leftArray);
mergeSort(rightArray);
//this calls the merge method to put the two halves together
merge(a, leftArray, rightArray);
}
private static void merge(int[] a, int[] leftHalf, int[] rightHalf)
{
int leftSize = leftHalf.Length;
int rightSize = rightHalf.Length;
int i = 0, j = 0, k = 0;
//loops until no more elements in left or right array
while(i < leftSize && j < rightSize)
{
if(leftHalf[i] <= rightHalf[j])
{
//sets the element at iteration k to the elements at i in the
left half if
//it is smaller than the right half
a[k] = leftHalf[i];
i++;
}
else
{
//if the right half is smaller, set element at iteration k
equal to the
//element at index j of the right half
a[k] = rightHalf[j];
j++;
}
k++;//iterate K
}
//these account for leftover elements after the above while loop.
while (i < leftSize)
{
a[k] = leftHalf[i];
i++;
k++;
}
while (j < rightSize)
{
a[k] = rightHalf[j];
j++;
k++;
}
}
My main method is here:
static void Main(string[] args)
{
try{
TextFileReader reader = new TextFileReader();
int[] numberArray = reader.ReadFile("numbers.txt");
//printArray(numberArray);
Sorts sorts = new Sorts();
//sorts.bubbleSort(numberArray);
//printArray(numberArray);
//sorts.selectionSort(numberArray);
Searches searches = new Searches();
//searches.SequentialSearch(numberArray, 897);
//searches.binarySearch(numberArray, 9992);
//Console.WriteLine("\n\nArray length: " + numberArray.Length);
mergeSort(numberArray);
printArray(numberArray);
}
catch(IOException ex)
{
Console.WriteLine("IO Exception Found.");
}
}
public static void printArray(int[] numberArray)
{
foreach(int i in numberArray)
{
Console.WriteLine(i);
}
}
}
}
This is driving me crazy because the other algorithms are working and outputting correctly, but when the MergeSort is ran it gives no exceptions or errors.
I have this situation:
int[] array = new int[] {7, 5, 6}
The value of my index i is 1 and it is pointing at the head of my hypothetical circular list. The value "7" at the zero position is the tail.
My aim is to print:
5,6,7
Do I need a specific structure or can I do it with a simple array?
With a single "for" loop and the modulo operator:
int[] array = new int[] {7, 5, 6};
int start = 1;
for (int idx=0; idx<array.Length; idx++)
Console.Write(array[(idx+start) % array.Length]);
There is nothing out of the box, but the following will wrap around the array.
int[] array = new int[] { 7, 5, 6 };
int startPosition = 1;
string result = "";
// Run from the start position to the end of the array
for (int i = startPosition; i < array.Length; i++)
{
result += array[i] + ",";
}
// Wrapping around, run from the beginning to the start position
for (int i = 0; i < startPosition; i++)
{
result += array[i] + ",";
}
// Output the results
result = result.TrimEnd(',');
Console.WriteLine(result);
Console.Read();
If you want to print 5,6,7 you could use:
int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
print(print(array[printIndex].ToString());
printIndex++;
if(printindex >= array.Length)
printindex = 0;
}
I Have an array, TempArray[] = {1,3,-1,5,7,-1,4,10,9,-1}
I want to remove every single -1 from this array and copy the remaining arrays into a new array called Original, which should output the numbers as 1,3,5,7,4,10,9
I can only use an if statement within a for loop!
This is what I have so far, but I keep getting an error message, System.IndexOutOfRangeException
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
//error occurs at this line
//My attempt is to set the new array, Original[i] equal to TempArray[i] only where the values are not -1.
TempArray[i] = Original[i];
}
}
If you can only use If statement in for loop. This looks like a school project. First you count how many non negative numbers are there in your array. Create new array with that length and fill that array.
int[] TempArray = new int[] {1,3,-1,5,7,-1,4,10,9,-1};
int[] Original ;
int countNonNegative=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
countNonNegative++;
}
}
Original = new int[countNonNegative];
int index=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[index] = TempArray[i];
index++;
}
}
Console.WriteLine("Original Length = "+Original.Length);
using System.Linq;
int[] withoutNegativeOnes = myArray
.Where(a => a != -1)
.ToArray();
var Original = new int[TempArray.Length];
var originalCounter = 0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[originalCounter++] = TempArray[i];
}
}
Now Original may contain empty spaces at the end though, but you have all the elements which aren't -1. You can use the following code to iterate through the values:
for (int i = 0; i < originalCounter; i++)
{
Console.WriteLine(Original[i]);
}
and that's because the originalCounter has the last index values that wasn't filled from TempArray's iteration.
try this one
int[] TempArray = { 1, 3, -1, 5, 7, -1, 4, 10, 9, -1 };
int[] original = TempArray.Where(i => i != -1).ToArray();
foreach(int i in original)
Console.WriteLine(i.ToString());
I have a text file that is being read in and then stored in a string[] which I then then convert into an int[], my bubblesort then should sort it but it doesn't because the values from the text files are decimals. So my question is how do I convert either the string[] or int[] to something that can accept decimal values, such as a double[] if there is such a thing. Thanks.
Code:
string[] sh1OpenData = File.ReadAllLines("SH1_Open.txt");
...
else if(input2.ToLower() == "open") //----
{
int[] intSh1OpenData = new int[sh1OpenData.Length];
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToInt32(sh1OpenData[x]);
}
Console.WriteLine("\n");
Console.WriteLine("Unsorted");
for (int i = 0; i < intSh1OpenData.Length; i++)
{
Console.Write(intSh1OpenData[i] + " ");
Console.WriteLine(" ");
}
int temp = 0;
for (int write = 0; write < intSh1OpenData.Length; write++)
{
for (int sort = 0; sort < intSh1OpenData.Length - 1; sort++)
{
if (intSh1OpenData[sort] > intSh1OpenData[sort + 1])
{
temp = intSh1OpenData[sort + 1];
intSh1OpenData[sort + 1] = intSh1OpenData[sort];
intSh1OpenData[sort] = temp;
}
}
}
Console.WriteLine("\n\n\nSORTED");
for (int i = 0; i < intSh1OpenData.Length; i++)
Console.Write(intSh1OpenData[i] + "\n");
}
You should not be using int to do comparisons on string. Use String.Compare(return 0 if equal, -1 if less than, or 1 if greater than) or List.Sort() to sort string array
Pretty simple with LINQ
var asDouble = sh1OpenData.Select(x => Double.Parse(x)).OrderBy(x => x).ToArray();
This will give you a sorted (ascending order) array of Double.
Note: this assumes that all of sh1OpenData can be parsed as a Double, and will throw an exception if not.
The only changes that you will need to make are listed below:
double[] intSh1OpenData = new double[sh1OpenData.Length]; // double[] instead of int[]
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToDouble(sh1OpenData[x]); // Convert to Double
}
also change the declaration of your temp variable to double temp;
Something that you could read through since you mentioned that you are new to programming:
C# Sort Arrays and Lists Examples
MSDN: List.Sort Method
I have an arranged array and I want to divide it into 3 parts so that their sum are closest to each other.
Ex: I have this array:
10, 8, 8, 7, 6, 6, 6, 5
so it'll be divided into 3 part like:
p1 {10,8} sum = 18
p2 {8,7,6} sum = 21
p3 {6,6,5} sum = 17
The original poster already has a working solution (noted in comments) to split the array into two parts with equal sums; call this split2. The three-part version can be constructed using split2.
Add to the array a new number equal to one-third of the sum of the original numbers.
Split the array into two parts using split2.
One part has the number that was added; remove it.
Split the other part into two using split2.
This is like two-Partition problem which is NP-Hard but not in strong sense, you can have an O(nK) algorithm for it where K is size of your input sum, See pseudo polynomial time algorithm for subset sum, Also See my answer for divide-list-in-two-parts-that-their-sum-closest-to-each-other, but in your case you should just add another dimension to process it.
// calculate total
total = 0;
for(i = 0; i != size; ++i) {
total += array[i];
}
// partition
n_partitions = 3;
current_partition = 1;
subtotal = array[0];
for(i = 1; i != size; ++i) {
if(subtotal + array[i] > total / n_partitions) {
// start new partition;
current_partition++;
subtotal = array[i];
} else {
// push to current partition
subtotal += array[i];
}
}
Try the following code
int total = 0, partSum = 0, partIndex = 0;
int noOfParts = 3; //Initialize the no. of parts
int[] input = { 10, 8, 8, 7, 6, 6, 6, 5 };
int[] result = new int[noOfParts]; //Initialize result array with no. of locations equal to no. of parts, to store partSums
foreach (int i in input) //Calculate the total of input array values
{
total += i;
}
int threshold = (total / noOfParts) - (total / input.Length) / 2; //Calculate a minimum threshold value for partSum
for (int j = input.Length - 1; j > -1; j--)
{
partSum += input[j]; //Add array values to partSum incrementally
if (partSum >= threshold) //If partSum reaches the threshold value, add it to result[] and reset partSum
{
result[partIndex] = partSum;
partIndex += 1;
partSum = 0;
continue;
}
}
if (partIndex < noOfParts) //If no. of parts in result[] is less than the no. of parts required, add the remaining partSum value
{
result[partIndex] = partSum;
}
Array.Reverse(result);
foreach (int k in result)
{
Console.WriteLine(k);
}
Console.Read();
I've tested this with various values in array(arranged in descending order) and also with different value for no. of parts(3,4,5...) and got good results.
Updated with code:
The approach I suggest is as follows (with code below):
Create data structures (Collections etc) to represent the number of output parts that you need (in your example 3)
Sort the input array in descending order.
Iterate through the elements of the input array and for each value:
pick an output part to place the value in (this should be the output part currently with the lowest overall sum..)
add the value to the selected output part
With the above logic, you will always be adding to the output part with the lowest overall value (which will help to keep the parts of similar overall value).
(in the code sample below I have skipped the array sorting step as your example is already sorted)
Code:
// the input array
int[] inputArray = new int[] { 10, 8, 8, 7, 6, 6, 6, 5 };
// the number of parts you want
int numberOfOutputParts = 3;
// create the part structures
List<Part> listOfParts = new List<Part>();
for(int i =0; i < numberOfOutputParts; i++)
{
listOfParts.Add(new Part());
}
// iterate through each input value
foreach (int value in inputArray)
{
// find the part with the lowest sum
int? lowestSumFoundSoFar = null;
Part lowestValuePartSoFar = null;
foreach(Part partToCheck in listOfParts)
{
if (lowestSumFoundSoFar == null || partToCheck.CurrentSum < lowestSumFoundSoFar)
{
lowestSumFoundSoFar = partToCheck.CurrentSum;
lowestValuePartSoFar = partToCheck;
}
}
// add the value to that Part
lowestValuePartSoFar.AddValue(value);
}
The code for the Part class used above (although you could use something better is as follows):
public class Part
{
public List<int> Values
{
get;
set;
}
public int CurrentSum
{
get;
set;
}
/// <summary>
/// Default Constructpr
/// </summary>
public Part()
{
Values = new List<int>();
}
public void AddValue(int value)
{
Values.Add(value);
CurrentSum += value;
}
}
Could you try my sample, this may help you
My Algorithm:
1/ Calculate avg value of the array numbers by the number of output array (exp:value=3 in your post)
2/ Sum the array numbers until the Sum has min gap compare to the avg value (calculated in 1/)
3/ Do step 2 until you go to the end of the array numbers
I using C# 3.5 to test
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
ArrayList inputValue = new ArrayList();
int avgValue = 0;
bool isFinish = false;
private void button1_Click(object sender, EventArgs e)
{
#region Init data
isFinish = false;
avgValue = 0;
inputValue.Clear();
listBox1.Items.Clear();
//assum you input valid number without space and in desc sorting order
string[] arrNumber = textBox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int numberOfBreak = 3;
int record = Convert.ToInt32(arrNumber[0]);//update the record with the maximum value of the array numbers
for (int i = 0; i < arrNumber.Length; i++)
{
inputValue.Add(Convert.ToInt32(arrNumber[i]));
}
foreach (object obj in inputValue)
{
avgValue += (int)obj;
}
avgValue = avgValue / numberOfBreak;
#endregion
int lastIndex = 0;
while (!isFinish)
{
int index = GetIndex(lastIndex);
string sResult = "";
for (int i = lastIndex; i <= index; i++)
{
sResult += inputValue[i].ToString() + "-";
}
listBox1.Items.Add(sResult);
if (index + 1 < inputValue.Count)
{
lastIndex = index + 1;
}
sResult = "";
}
}
private int GetIndex(int startIndex)
{
int index = -1;
int gap1 = Math.Abs(avgValue - (int)inputValue[startIndex]);
int tempSum = (int)inputValue[startIndex];
if (startIndex < inputValue.Count - 1)
{
int gap2 = 0;
while (gap1 > gap2 && !isFinish)
{
for (int i = startIndex + 1; i < inputValue.Count; i++)
{
tempSum += (int)inputValue[i];
gap2 = Math.Abs(avgValue - tempSum);
if (gap2 <= gap1)
{
gap1 = gap2;
gap2 = 0;
index = i;
if (startIndex <= inputValue.Count - 1)
{
startIndex += 1;
}
else
{
isFinish = true;
}
if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
break;
}
else
{
index = i - 1;
break;
}
}
}
}
else if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
else
{
isFinish = true;
}
return index;
}
}
}