C# Linked Lists (adding an element to a defined position) - c#

Our teacher asked us to implement the class LinkedList. I was able to implement everything he asked for. But he gave us a bonus question that I was not able to solving.
He asked us to implement this fonction:
public void add(float x, int pos)
{
// Add x at the position pos, pos = 0 refer to the first element.
}
He also demanded that his code verifies the following UnitTest:
public class UnitTest1
{
private MyList l;
public UnitTest1()
{
l = new MyList();
for (int i = 0; i < 10; ++i)
{
l.add(i * i);
}
for (int i = 0; i < 10; ++i)
{
l.add(i * i);
}
}
[TestMethod]
public void TestAdd()
{
Assert.AreEqual(l.count(), 20);
}
[TestMethod]
public void TestGet()
{
for (int i = 0; i < 10; ++i)
{
Assert.AreEqual(l.get(i), (9 - i) * (9 - i));
}
for (int i = 10; i < 20; ++i)
{
Assert.AreEqual(l.get(i), (19 - i) * (19 - i));
}
}
[TestMethod]
public void TestFind()
{
int k;
for (int i = 0; i < 100; ++i)
{
for (k = 0; k < 10; ++k)
{
if (k * k == i)
{
Assert.AreEqual(l.find(i), true);
break;
}
}
if (k == 10)
{
Assert.AreEqual(l.find(i), false);
}
}
}
[TestMethod]
public void TestStats()
{
Assert.AreEqual(l.max(), 81);
float s = 0;
for (int i = 0; i < 10; ++i)
{
s += i * i + i * i;
}
Assert.AreEqual(l.sum(), s);
Assert.AreEqual(l.average(), s / 20);
}
[TestMethod]
public void TestCountValue()
{
MyList l1 = new MyList();
for (int i = 0; i < 10; ++i)
{
l1.add(i);
l1.add(i * i);
}
Assert.AreEqual(l1.count(-1), 0);
Assert.AreEqual(l1.count(0), 2);
Assert.AreEqual(l1.count(1), 2);
Assert.AreEqual(l1.count(2), 1);
Assert.AreEqual(l1.count(3), 1);
Assert.AreEqual(l1.count(4), 2);
Assert.AreEqual(l1.count(5), 1);
Assert.AreEqual(l1.count(6), 1);
Assert.AreEqual(l1.count(7), 1);
Assert.AreEqual(l1.count(8), 1);
Assert.AreEqual(l1.count(9), 2);
Assert.AreEqual(l1.count(10), 0);
Assert.AreEqual(l1.count(16), 1);
}
[TestMethod]
public void TestRemoveFirst()
{
MyList l1 = new MyList();
for (int i = 0; i < 10; ++i)
{
l1.add(i);
l1.add(i * i);
}
Assert.AreEqual(l1.count(81), 1);
l1.removeFirst();
Assert.AreEqual(l1.count(), 19);
Assert.AreEqual(l1.count(81), 0);
Assert.AreEqual(l1.count(-1), 0);
Assert.AreEqual(l1.count(0), 2);
Assert.AreEqual(l1.count(1), 2);
Assert.AreEqual(l1.count(2), 1);
Assert.AreEqual(l1.count(3), 1);
Assert.AreEqual(l1.count(4), 2);
Assert.AreEqual(l1.count(5), 1);
Assert.AreEqual(l1.count(6), 1);
Assert.AreEqual(l1.count(7), 1);
Assert.AreEqual(l1.count(8), 1);
Assert.AreEqual(l1.count(9), 2);
Assert.AreEqual(l1.count(10), 0);
Assert.AreEqual(l1.count(16), 1);
}
[TestMethod]
public void TestInsert()
{
MyList l1 = new MyList();
for (int i = 9; i >= 0; --i)
{
l1.add(i);
}
for (int i = 0; i <= 10; ++i)
{
l1.add(i, 2 * i);
}
for (int i = 0; i < 10; ++i)
{
Assert.AreEqual(l1.get(2 * i), i, "i=" + i);
Assert.AreEqual(l1.get(2 * i + 1), i);
}
Assert.AreEqual(l1.get(20), 10);
}
}
That's what I was capable of:
public class MyList
{
class Element
{
public float value;
public Element next;
}
Element first;
public MyList()
{
first = null;
}
public void add(float x)
{
Element e = new Element();
e.value = x;
e.next = first;
first = e;
}
public float get(int i)
{
if (first == null)
{
throw new Exception("Empty list... no elements inside");
}
Element tmp = first;
for (int j = 0; j < i; ++j)
{
tmp = tmp.next;
if (tmp == null)
{
throw new Exception("...");
}
}
return tmp.value;
}
public void print()
{
Element e = first;
while (e != null)
{
Console.WriteLine(e.value);
e = e.next;
}
}
public bool find(float x)
{
Element e = first;
while (e != null)
{
if (e.value == x)
{
return true;
}
e = e.next;
}
return false;
}
public float max()
{
float G = 0;
for (Element e = first; e != null; e = e.next)
{
if (e.value > G)
{
G = e.value;
}
}
return G;
}
public int count()
{
Element e = first;
int c = 0;
while (e != null)
{
c++;
e = e.next;
}
return c;
}
public int count(float x)
{
int c = 0;
for (Element e = first; e != null; e = e.next)
{
if (e.value == x)
{
c++;
}
}
return c;
}
public float sum()
{
float S = 0;
for (Element e = first; e != null; e = e.next)
{
S += e.value;
}
return S;
}
public float average()
{
return sum() / count();
}
public void removeFirst()
{
Element e = first;
first = e.next;
}
public void add(float x, int pos)
{
//I have absolutely no idea how to implement this fonction.
}
}

It will be similar to the code in the get() method.
Break your problem down into smaller problems
Does pos = 0?
if so, create a new root and point it to the old root
if not, loop (pos) times and create a new element. Then set the next property of the new element to the next property of the current element. Set the current element next property to your new element
.
public void add(float x, int pos)
{
if(pos == 0)
{
// create a new root and point the new root to the existing root
}
else
{
Element tmp = first;
for(int i = 0; i < pos; i++)
{
tmp = tmp.next;
}
// create new element
// set new element next property to tmp.next
// set tmp.next to new element
}
}

Related

how can i have the high score in 1st in Tetris?

I got some problem with my Tetris game on highscore, here's the game script
/// The width of the Grid...
public static int gridWidth = 10;
/// The weight of the Grid...
public static int gridWeight = 20;
/// The grid...
public static Transform[,] grid = new Transform[gridWidth, gridWeight];
public static bool startingAtLevelZero;
public static int startingLevel;
public int scoreOneLine = 50;
public int scoreTwoLine = 100;
public int scoreThreeLine = 400;
public int scoreFourLine = 1500;
public int currentLevel = 0;
private int numLinesCleared = 0;
public static float fallSpeed = 1.0f;
public AudioClip clearedLineSound;
public Text hud_score;
public Text hud_level;
public Text hud_lines;
private int numberOfRowsThisTurn = 0;
private AudioSource audioSource;
public static int currentScore = 0;
private GameObject previewTetromino;
private GameObject nextTetromino;
private bool gameStarted = false;
private int startingHighScore;
private int startingHighScore2;
private int startingHighScore3;
private Vector2 previewTetrominoPosition = new Vector2(-6.5f, 16);
// Start is called before the first frame update
void Start()
{
currentScore = 0;
hud_score.text = "0";
currentLevel = startingLevel;
hud_level.text = currentLevel.ToString();
hud_lines.text = "0";
SpawnNextTetromino();
audioSource = GetComponent<AudioSource>();
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
}
void Update()
{
UpdateScore();
UpdateUI();
UpdateLevel();
UpdateSpeed();
}
void UpdateLevel()
{
if ((startingAtLevelZero == true) || (startingAtLevelZero == false && numLinesCleared / 10 > startingLevel))
currentLevel = numLinesCleared / 10;
Debug.Log("current Level : " + currentLevel);
}
void UpdateSpeed()
{
fallSpeed = 1.0f - ((float)currentLevel * 0.1f);
Debug.Log("current Fall Speed : " + fallSpeed);
}
public void UpdateUI()
{
hud_score.text = currentScore.ToString();
hud_level.text = currentLevel.ToString();
hud_lines.text = numLinesCleared.ToString();
}
public void UpdateScore()
{
if (numberOfRowsThisTurn > 0)
{
if (numberOfRowsThisTurn == 1)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 2)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 3)
{
ClearedThreeLine();
}
else if (numberOfRowsThisTurn == 4)
{
ClearedFourLine();
}
numberOfRowsThisTurn = 0;
PlayLineClearedSound();
}
}
public void ClearedOneLine()
{
currentScore += scoreOneLine + (currentLevel * 20);
numLinesCleared++;
}
public void ClearedTwoLine()
{
currentScore += scoreTwoLine + (currentLevel * 25);
numLinesCleared += 2;
}
public void ClearedThreeLine()
{
currentScore += scoreThreeLine + (currentLevel * 30);
numLinesCleared += 3;
}
public void ClearedFourLine()
{
currentScore += scoreFourLine + (currentLevel * 40);
numLinesCleared += 4;
}
public void PlayLineClearedSound()
{
audioSource.PlayOneShot(clearedLineSound);
}
public void UpdateHighScore()
{
if (currentScore > startingHighScore)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highScore2", startingHighScore);
PlayerPrefs.SetInt("highscore", currentScore);
}
else if (currentScore > startingHighScore2)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highscore2", currentScore);
}
else if (currentScore > startingHighScore3)
{
PlayerPrefs.SetInt("highscore3", currentScore);
}
}
public bool CheckIsAboveGrid(Tetromino tetromino)
{
for (int x = 0; x < gridWidth; ++x)
{
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y > gridWeight - 1)
{
return true;
}
}
}
return false;
}
public bool IsFullRowAt (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid [x, y] == null)
{
return false;
}
}
numberOfRowsThisTurn++;
return true;
}
public void DeleteMinoAt(int y)
{
for (int x = 0; x < gridWidth; ++x)
{
Destroy(grid[x, y].gameObject);
grid[x, y] = null;
}
}
public void MoveRowDown (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
grid[x,y -1] = grid[x, y];
grid[x, y] = null;
grid[x, y -1].position += new Vector3(0, -1, 0);
}
}
}
public void MoveAllRowsDown (int y)
{
for (int i = y; i < gridWeight; ++i)
{
MoveRowDown(i);
}
}
public void DeleteRow()
{
for (int y = 0; y < gridWeight; ++y)
{
if (IsFullRowAt(y))
{
DeleteMinoAt(y);
MoveAllRowsDown(y + 1);
--y;
}
}
}
public void UpdateGrid (Tetromino tetromino)
{
for (int y = 0; y < gridWeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
if (grid[x,y].parent == tetromino.transform)
{
grid[x, y] = null;
}
}
}
}
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y < gridWeight)
{
grid[(int)pos.x, (int)pos.y] = mino;
}
}
}
public Transform GetTransformAtGridPosition (Vector2 pos)
{
if (pos.y > gridWeight -1)
{
return null;
}
else
{
return grid[(int)pos.x, (int)pos.y];
}
}
public void SpawnNextTetromino()
{
if (!gameStarted)
{
gameStarted = true;
nextTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), new Vector2(5.0f, 20.0f), Quaternion.identity);
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
else
{
previewTetromino.transform.localPosition = new Vector2(5.0f, 20.0f);
nextTetromino = previewTetromino;
nextTetromino.GetComponent<Tetromino>().enabled = true;
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
}
public bool CheckIsInsideGrid (Vector2 pos)
{
return ((int)pos.x >= 0 && (int)pos.x < gridWidth && (int)pos.y >= 0);
}
public Vector2 Round (Vector2 pos)
{
return new Vector2(Mathf.Round(pos.x), Mathf.Round(pos.y));
}
string GetRandomTetromino()
{
int randomTetromino = Random.Range(1, 8);
string randomTetrominoName = "Prefabs/Tetromino_T";
switch (randomTetromino)
{
case 1:
randomTetrominoName = "Prefabs/Tetromino_T";
break;
case 2:
randomTetrominoName = "Prefabs/Tetromino_Long";
break;
case 3:
randomTetrominoName = "Prefabs/Tetromino_Square";
break;
case 4:
randomTetrominoName = "Prefabs/Tetromino_J";
break;
case 5:
randomTetrominoName = "Prefabs/Tetromino_L";
break;
case 6:
randomTetrominoName = "Prefabs/Tetromino_S";
break;
case 7:
randomTetrominoName = "Prefabs/Tetromino_Z";
break;
}
return randomTetrominoName;
}
public void GameOver()
{
UpdateHighScore();
Application.LoadLevel("GameOver");
}
and here's the game menu script
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
highScoreText2.text = PlayerPrefs.GetInt("highscore2").ToString();
highScoreText3.text = PlayerPrefs.GetInt("highScore3").ToString();
}
public void PlayGame()
{
if (Game.startingLevel == 0)
Game.startingAtLevelZero = true;
else
Game.startingAtLevelZero = false;
Application.LoadLevel("tetris");
}
public void ChangedValue (float value)
{
Game.startingLevel = (int)value;
levelText.text = value.ToString();
}
public void LaunchGameMenu()
{
Application.LoadLevel("tetris menu");
}
When I got 1120 score in the Tetris game, it shows up in 2nd score instead of 3rd or 1st ,when I got 720 score, it doesn't show up in 3rd score, when I score 1300 It shows up in 2nd and 1120 in 3rd, but not in 1st, can somehow help me what is wrong?
It appears you have various typographical errors while typing the keys when accessing the player's PlayerPrefs. PlayerPrefs is case-sensitive.
↓↓↓
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
...
↓↓↓
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
Consider the use of the nameof() command. The nameof() command allows you to treat a variable in-code as a string. This is SUPER helpful if you ever re-name the variable for example, the string will be renamed along with it. It also has the added bonus of giving you compilation errors if they are misspelled.
Example:
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt(nameof(highScoreText)).ToString();
highScoreText2.text = PlayerPrefs.GetInt(nameof(highScoreText2)).ToString();
highScoreText3.text = PlayerPrefs.GetInt(nameof(highScoreText3)).ToString();
}

Creating A Linked List. C#

I've tried creating linked list/node classes and I'm not sure where to go next. My attempts haven't went well because after creating the classes I'm just not sure what the next step is.
I'm trying to create a program that has a dinosaur node which saves information about the dinosaur such as id, species etc and I want to allow the user to create and remove dinosaurs from the list. So I need to allow the user to input data, I assume there's a way to make dino id get set automatically but I'm not to sure.
I've included the LinkedList.cs and the Node.cs so you can see where I'm going but I have no idea what to do within my program class to utilise the linked list and achieve what I'm trying to do.
Added Program.cs class incase that helps identify/show where I am within the program/what I need to do.
Linked List Class:
using System;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
using System.Text;
namespace JurrasicFinal
{
public class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
this.head = null;
this.count = 0;
}
public bool Empty
{
get { return this.count == 0; }
}
public int Count
{
get { return this.count; }
}
public object this[int index]
{
get { return this.Get(index); }
}
public object Add(int index, object o)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (index > count)
index = count;
Node current = this.head;
if (this.Empty || index == 0)
{
this.head = new Node(o, this.head);
}
else
{
for (int i = 0; i < index - 1; i++)
{
current = current.Next;
current.Next = new Node(o, current.Next);
}
}
count++;
return o;
}
public object Add(object o)
{
return this.Add(count, o);
}
public object Remove(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return null;
if (index >= this.count)
index = count - 1;
Node current = this.head;
object result = null;
if (index == 0)
{
result = current.Data;
this.head = current.Next;
}
else
{
for (int i = 0; index < index - 1; i++) ;
current = current.Next;
result = current.Next.Data;
current.Next = current.Next.Next;
}
count--;
return result;
}
public void Clear()
{
this.head = null;
this.count = 0;
}
public int IndexOf(object o)
{
Node current = this.head;
for (int i = 0; i < this.count; i++)
{
if (current.Data.Equals(o))
return i;
current = current.Next;
}
return -1;
}
public bool Contains(object o)
{
return this.IndexOf(o) >= 0;
}
public object Get(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return null;
if (index >= this.count)
index = this.count - 1;
Node current = this.head;
for (int i = 0; i < index; i++)
current = current.Next;
return current.Data;
}
}
}
Node Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace JurrasicFinal
{
public class Node
{
private object data;
private Node next;
private string DinoSpecies;
private string DinoName;
public Node(object data, Node next)
{
this.data = data;
this.next = next;
}
public object Data
{
get { return this.data; }
set { this.data = value; }
}
public Node Next
{
get { return this.next; }
set { this.next = value; }
}
}
}
Program Class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
namespace JurrasicFinal
{
class Program
{
class Dinosaur
{
public string Name;
public string Classification;
public char Sex;
}
static void Main(string[] args)
{
LinkedList<Dinosaur> DinoList = new LinkedList<Dinosaur>();
Dinosaur Dino1 = new Dinosaur();
Dino1.Name = "Tyrannosaurus Rex";
Dino1.Classification = "Carnivorous";
Dino1.Sex = 'M';
Dinosaur Dino2 = new Dinosaur();
Dino2.Name = "Velociraptor";
Dino2.Classification = "Carnivorous";
Dino2.Sex = 'F';
Dinosaur Dino3 = new Dinosaur();
Dino3.Name = "Procompsognathus";
Dino3.Classification = "Carnivorous";
Dino3.Sex = 'M';
void printList()
{
Console.WriteLine("Current Queue: ");
Console.WriteLine("\n");
foreach (Dinosaur d in DinoList)
{
Console.WriteLine("Name: " + d.Name);
Console.WriteLine("Classification: " + d.Classification);
Console.WriteLine("Sex " + d.Sex);
Console.WriteLine("\n");
}
Console.WriteLine(Dino1.Name + Dino1.Sex);
}
DinoList.AddLast(Dino1);
DinoList.AddLast(Dino2);
DinoList.AddLast(Dino3);
printList();
Console.WriteLine(DinoList.Count);
FileStream fileStream = File.OpenWrite("E:/Work/Dinosaur.txt");
BinaryWriter writer = new BinaryWriter(fileStream);
foreach (Dinosaur d in DinoList)
{
writer.Write(d.Name);
writer.Write(d.Classification);
writer.Write(d.Sex);
}
writer.Close();
Console.WriteLine("Reading Back From File");
FileStream file = File.OpenRead("E:/Work/Dinosaur.txt");
BinaryReader reader = new BinaryReader(file);
for (int i = 1; i < 3; i++)
{
Dinosaur d = new Dinosaur();
d.Name = reader.ReadString();
d.Classification = reader.ReadString();
d.Sex = reader.ReadChar();
DinoList.AddLast(d);
}
reader.Close();
Console.ReadKey();
}
}
}
I think you might be looking for something like this, which hangs on user input and tries to do simple validation. I made it a bit overly complex to demonstrate some options.
class Sample
{
private static int index = 0;
static void Main(string[] args)
{
LinkedList<Dinosaur> DinoList = new LinkedList<Dinosaur>();
while (true)
{
var dino = new Dinosaur();
dino.Name = GetInput("Enter dino name (q to quit): ");
if (dino.Name == "q" || dino.Name == "Q")
{
break;
}
dino.Classification = GetInput("Enter dino classification: ");
char[] sexes = new char[] {'F', 'f', 'M', 'm'};
while (true)
{
Console.WriteLine("Enter dino sex (M/F): ");
dino.Sex = (char) Console.Read();
if (sexes.Contains(dino.Sex))
{
break;
}
}
int inputIndex = default;
while (true)
{
var indexString = GetInput($"Enter 0-index list position (max {DinoList.Count})");
inputIndex = Convert.ToInt32(indexString);
if (inputIndex <= DinoList.Count)
{
break;
}
}
DinoList.Add(inputIndex, dino);
index++;
Console.WriteLine("Dinosaurs:");
Console.WriteLine(new string('-', 30));
for (var i = 0; i < DinoList.Count; i++)
{
var dinosaur = (Dinosaur) DinoList.Get(i);
Console.WriteLine("Name: " + dinosaur.Name);
Console.WriteLine("Classification: " + dinosaur.Classification);
Console.WriteLine("Sex: " + dinosaur.Sex);
}
}
}
private static string GetInput(string prompt)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
input = Console.ReadLine();
}
return input;
}
}
Note that you have to make your LinkedList and Node into LinkedList<T> and Node<T> but they converted directly, so it's just a bit of typing.
Hope it helps!
Edit: Add classes provided in question, modified to be generic.
public class Node<T>
{
private object data;
private Node<T> next;
private string DinoSpecies;
private string DinoName;
public Node(object data, Node<T> next)
{
this.data = data;
this.next = next;
}
public object Data
{
get { return this.data; }
set { this.data = value; }
}
public Node<T> Next
{
get { return this.next; }
set { this.next = value; }
}
}
public class LinkedList<T>
{
private Node<T> head;
private int count;
public LinkedList()
{
this.head = null;
this.count = 0;
}
public bool Empty
{
get { return this.count == 0; }
}
public int Count
{
get { return this.count; }
}
public object this[int index]
{
get { return this.Get(index); }
}
public object Add(int index, object o)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (index > count)
index = count;
Node<T> current = this.head;
if (this.Empty || index == 0)
{
this.head = new Node<T>(o, this.head);
}
else
{
for (int i = 0; i < index - 1; i++)
{
current = current.Next;
current.Next = new Node<T>(o, current.Next);
}
}
count++;
return o;
}
public object Add(object o)
{
return this.Add(count, o);
}
public object Remove(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return null;
if (index >= this.count)
index = count - 1;
Node<T> current = this.head;
object result = null;
if (index == 0)
{
result = current.Data;
this.head = current.Next;
}
else
{
for (int i = 0; index < index - 1; i++) ;
current = current.Next;
result = current.Next.Data;
current.Next = current.Next.Next;
}
count--;
return result;
}
public void Clear()
{
this.head = null;
this.count = 0;
}
public int IndexOf(object o)
{
Node<T> current = this.head;
for (int i = 0; i < this.count; i++)
{
if (current.Data.Equals(o))
return i;
current = current.Next;
}
return -1;
}
public bool Contains(object o)
{
return this.IndexOf(o) >= 0;
}
public object Get(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return null;
if (index >= this.count)
index = this.count - 1;
Node<T> current = this.head;
for (int i = 0; i < index; i++)
current = current.Next;
return current.Data;
}
}

Checking if singly-linked list is palindrome or not

This is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedList
{
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
next = null;
}
}
public class MyList
{
public Node head;
public MyList()
{
head = null;
}
public void addNode(int data)
{
if(head == null)
{
head = new Node(data);
}
else
{
Node temp = new Node(data);
Node current = head;
while(current.next != null)
{
current = current.next;
}
current.next = temp;
}
}
public void print()
{
if(head == null)
{
Console.WriteLine("List is already empty!");
}
else
{
Node current = head;
while (current != null)
{
Console.Write("|" + current.data + "|-> ");
current = current.next;
}
Console.WriteLine();
}
}
public void addToStart(int data)
{
if(head == null)
{
head = new Node(data);
}
else
{
Node temp = new Node(data);
temp.next = head;
head = temp;
}
}
public void addSorted(int data)
{
if(head == null)
{
head = new Node(data);
}
else if(data < head.data)
{
addToStart(data);
}
else
{
Node current = head.next;
Node previous = head;
Node temp = new Node(data);
while(current != null)
{
if(data < current.data)
{
previous.next = temp;
temp.next = current;
break;
}
previous = current;
current = current.next;
}
}
}
public void removeLast()
{
if(head == null)
{
Console.WriteLine("List is already empty!");
}
else if(head.next == null)
{
head = null;
}
else
{
Node current = head.next;
Node previous = head;
while(current.next != null)
{
previous = current;
current = current.next;
}
previous.next = null;
}
}
public bool isPalindrome()
{
List<int> arr1 = new List<int>();
int i = 0;
Node current = head;
while (current != null)
{
arr1.Add(current.data);
current = current.next;
i++;
}
int[] arr3 = arr1.ToArray();
int count = i;
int[] arr2 = new int[count];
int j = 0;
for (int x = i - 1; x >= 0; x--)
{
arr2[j] = arr3[x];
}
for (int k = 0; k < count; k++)
{
if (arr3[k] != arr2[k])
{
return false;
}
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
MyList a = new MyList();
a.addNode(1);
a.addNode(2);
a.addNode(5);
a.addNode(2);
a.addNode(1);
a.print();
if(a.isPalindrome())
{
Console.WriteLine("Linked List is Palindrome!");
}
else
{
Console.WriteLine("Linked List is Not Palindrome!");
}
}
}
}
My code returns false for the palindrome function every time except when I enter only one value in the linked list.
Also let me know if my method of List<int> is okay or not because I needed it for the palindrome check.
Thankyou for your comments, This is how i solved it.
public bool isPalindrome()
{
int i = 0;
Node current = head;
Node temp = head;
while (temp != null)
{
temp = temp.next;
i++;
}
int[] arr1 = new int[i];
int count = i;
for (int j = 0; j < count; j++)
{
arr1[j] = current.data;
current = current.next;
}
int[] arr2 = new int[count];
int z = 0;
for (int x = i - 1; x >= 0; x--)
{
arr2[z] = arr1[x];
z++;
}
for (int x = 0; x < count; x++)
{
if (arr1[x] != arr2[x])
{
return false;
}
}
return true;
}

Finding minimum value from list

How would i build an algorithm here in the most efficient way possible to find minimum value from list? I know the list hasnt done in the best way but, any ideas how to do ?
I have tried few ways but dont seem to get it work efficiently..
Thanks.
class MainClass
{
public class List
{
public int maxSize = 50;
public int MaxSize
{
get
{
return maxSize;
}
set
{
maxSize = value;
}
}
public int firstEmpty = 0;
public int FirstEmpty
{
get
{
return firstEmpty;
}
set
{
firstEmpty = value;
}
}
public int[] data;
public List()
{
data = new int[maxSize];
}
public int returnValueAtIndex(int i)
{
return data[i];
}
public void setValueAtIndex(int v, int i)
{
data[i] = v;
}
}
public static int FIRST(List L)
{
if (END(L) > 0)
return 0;
else
return -1;
}
public static int END(List L)
{
return L.FirstEmpty;
}
public static int NEXT(int p, List L)
{
if (p >= 0 && p < L.MaxSize && p < END(L))
return p+1;
else
return - 1;
}
public static int PREVIOUS(int p, List L)
{
if (p >= 0 && p < L.MaxSize && p <= END(L))
return p-1;
else
return -1;
}
public static int LOCATE (int x, List L)
{
int i = 0;
while (i<END(L) && RETRIEVE(i, L) != x)
{
i++;
}
if (i != END(L))
return i;
else
return -1;
}
public static int RETRIEVE(int p, List L)
{
if (p >= 0 && p < END(L))
return L.returnValueAtIndex(p);
else
return -1;
}
public static void INSERT(int x, int p, List L)
{
if (p >= 0 && p < L.MaxSize && p <= END(L))
{
if (p == END(L))
{
L.setValueAtIndex(x, p);
}
else
{
for (int i = END(L); i > p; i--)
{
L.setValueAtIndex(L.returnValueAtIndex(i - 1), i);
L.setValueAtIndex(x, p);
}
}
L.FirstEmpty = END(L) + 1;
}
else
Console.WriteLine("Alkiota ei voitu lisätä");
}
public void DELETE(int p, List L)
{
if (p >= 0 && p < END(L))
{
for (int i = p; i < p - 1; i++)
{
L.setValueAtIndex(L.returnValueAtIndex(i + 1), i);
}
L.FirstEmpty = END(L) - 1;
}
}
public void MAKENULL(List L)
{
L.FirstEmpty = 0;
}
public static void PRINT(List L)
{
Console.WriteLine("Listan sisältö:");
for (int i = 0; i < END(L); i++)
{
Console.Write(L.returnValueAtIndex(i) + " ");
}
Console.WriteLine();
}
public static void Main(string[] args)
{
List testilista = new List();
INSERT(2, END(testilista), testilista);
INSERT(7, END(testilista), testilista);
INSERT(9, END(testilista), testilista);
INSERT(12, END(testilista), testilista);
INSERT(9, END(testilista), testilista);
INSERT(38, END(testilista), testilista);
Console.WriteLine("testilista");
PRINT(testilista);
Console.ReadLine();
}
}
}
The easiest way to do that in C# is with LinQ:
var minValue = data.Min();
if you want the highest value:
var maxValue = data.Max();
Note: Answer is not specific to C#
Given an unordered list of numbers, the fastest way to find the smallest number in the list is to look at every element in the list.
var unorderedList = [5,4,3,2,6,7,-23,8,-64,2,0,6];
function findSmallest(anArray){
var lowest = anArray[0];
for(var i = 1; i < anArray.length; i++){
var num = anArray[i];
if(num < lowest){
lowest = num;
}
}
return lowest;
}
var smallest = findSmallest(unorderedList);
console.log(smallest); //prints -64
You can run the code here
hit the run button
I don't think this is the best option. For me there is two ways.
Sort your list by this code.
int valueMin = L.returnValueAtIndex(0);
for (int i = 0; i < END(L); i++)
{
//if the value of i is smaller than the value
if (valueMin < L.returnValueAtIndex(i))
{
//i become the min Value
valueMin = L.returnValueAtIndex(i);
}
}
Console.WriteLine(valueMin);
Console.Read();
Or in C# you can use Array.Sort
Array.Sort(L);
Console.WriteLine(L.returnValueAtIndex(0));
Console.Read();
I hope this will help you !

How many swaping & comparsions in each sorting algorithm?

class Sort
{
int[] arr;
int counter=0;
//Constructor
public Sort()
{
arr = new int[10000];
}
string address;
public void SwitchCase(int Case)
{
switch (Case)
{
case 1:
address = #"C:\Users\Aqib Saeed\Desktop\case1.txt";
break;
case 2:
address = #"C:\Users\Aqib Saeed\Desktop\case2.txt";
break;
case 3:
address = #"C:\Users\Aqib Saeed\Desktop\case3.txt";
break;
default:
break;
}
}
//Read file for input
public void FillArray()
{
using (StreamReader rdr = new StreamReader(address))
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToInt32(rdr.ReadLine());
}
}
}
// Insertion Sort
public void InsertionSort()
{
int insert;
for (int i = 1; i < arr.Length; i++)
{
insert = arr[i];
int moveItem = i;
while (moveItem > 0 && arr[moveItem - 1] > insert)
{
arr[moveItem] = arr[moveItem - 1];
moveItem--;
counter++;
}
arr[moveItem] = insert;
}
}
public void Counter()
{
Console.WriteLine(counter);
}
//Bubble Sorting
public void BubbleSort()
{
int temp;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
counter++;
}
}
}
}
//Selection Sorting
public void SelectionSort()
{
int min, temp;
for (int i = 0; i < arr.Length; i++)
{
min = i;
for (int j = i + 1; j < arr.Length; j++)
if (arr[j] < arr[min])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
counter++;
}
}
// Write Output to file
public void Writer()
{
using (StreamWriter wrtr = new StreamWriter(#"C:\Users\AqibSaeed\Desktop\SortedOutput.txt"))
{
for (int i = 0; i < arr.Length; i++)
{
wrtr.WriteLine(arr[i]);
}
}
}
}
static void Main(string[] args)
{
Sort srt = new Sort();
Console.WriteLine("Enter Case 1 OR 2 OR 3");
srt.SwitchCase(Convert.ToInt32(Console.ReadLine()));
srt.FillArray();
srt.BubbleSort();
srt.Writer();
Console.WriteLine("Sorted Output File Is Ready");
srt.Counter();
Console.ReadLine();
}
I implement my Sort class for sorting integers and place int counter to determine number of swaps and comparsions. But I am not sure it is working correctly! Is there any other way to determine number of swaping and comparsions?
You could create a class which implements IComparable to count the comparator access and a specialized collection which counts the swaps. Like that you dont have to count the access inside of the sort algorithms and you delegate the tasks more strict to code parts.
In the index operator you count the swap operations and in the IComparable implementation you count the comparisons
Example for a class SortItem which implements the IComparable:
public class SortItem<T> : IComparable<T> where T : IComparable
{
private static int _ComparisonCount = 0;
public static int ComparisonCount
{
private set
{
_ComparisonCount = value;
}
get
{
return _ComparisonCount;
}
}
public T Value
{
get;
set;
}
public static void ResetComparisonCount()
{
_ComparisonCount = 0;
}
#region IComparable<T> Members
public int CompareTo(T other)
{
ComparisonCount++;
return this.Value.CompareTo(other);
}
#endregion
}
and the sorting collection:
public class SortCollection<T> : IList<SortItem<T>>
{
public SortCollection(IList<T> sortList)
{
InnerList = sortList;
}
private IList<T> InnerList = null;
public T this[int key]
{
get
{
return InnerList[key];
}
set
{
SwapCount++;
InnerList[key] = value;
}
}
private int _SwapCount = 0;
public int SwapCount
{
private set
{
_SwapCount = value;
}
get
{
return _SwapCount;
}
}
public void ResetSwapCount()
{
_SwapCount = 0;
}
}
Here the execution:
List<Int32> baseList = new List<int>(new Int32 {6, 2, 7, 3, 1, 6, 7 });
SortCollection<Int32> sortList = new SortCollection<int>(baseList);
//do the sorting....
Console.WriteLine("Swaps: " + sortList.SwapCount.ToString());
Console.WriteLine("Comparisons: " + SortItem<Int32>.ComparisonCount.ToString());
SortItem<Int32>.ResetComparisonCount();
sortList.ResetSwapCount();
You are only counting swaps and not counting comparisons. If you want to count comparisons then you need to add an extra counter that you increment every time you pass an if comparison.

Categories

Resources