可以在自定义的抽象数据类型(有序链表)中使用两种数据类型吗?

huangapple go评论79阅读模式
英文:

Is it possible to use 2 Data Type in an Custom ADT(Sorted Linked List)?

问题

我试图通过使用排序链表Sorted Linked List来实现一个游戏的排行榜我已经成功地按照分数降序排列这意味着分数从高到低排序此外我还需要将玩家姓名与分数一起放入排行榜中问题出在这里我实现的排序链表SLL是整数数据类型它在整数数据类型上运行得很好因为它可以对数字进行排序

```java
SortedListInterface<Integer> Player = new LeaderboardSortedLinkedList<Integer>();

但是,当我尝试放入玩家姓名(使用字符串)时,由于分数数据类型需要与玩家姓名的数据类型一致,所以无法实现。以下是驱动类的代码:

public class testLeaderboard {

   
    public static void main(String[] args) {
        SortedListInterface<Integer> Player = new LeaderboardSortedLinkedList<Integer>();
        
            Player.add(1000000);
            Player.add(500000);
            // 其他分数的添加...
        
        System.out.printf("=================================\n" 
                         + "          Leaderboard\n"
                         +"=================================\n");
        
        for(int i=0; i < Player.size(); i++){
            
            System.out.printf("%3d. %s\n",(i+1), Player.get(i+1));
        }
        
    }
    
}

这是实体类:

public class Player {
    private String name;
    private int prize;

    public Player(String name, int prize) {
        this.name = name;
        this.prize = prize;
    }

    // 各种 getter 和 setter...

    @Override
    public String toString() {
        return "Player{" + "name=" + name + ", prize=" + prize + '}';
    }
}

以下是自定义的排序链表:

public class LeaderboardSortedLinkedList<T extends Comparable<T>> implements SortedListInterface<T> {

    // 其他代码...

    public boolean add(T newEntry) {
        // 添加新元素的代码...
    }

    // 其他方法...

    private class Node {

        private T data;
        private Node next;

        private Node(T data) {
            this.data = data;
            next = null;
        }

        private Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}

要同时支持字符串和整数的排名,您可以修改 LeaderboardSortedLinkedList 类以存储 Player 对象,而不仅仅是整数。这样,您可以按照玩家的分数进行排序。以下是可能的修改:

public class LeaderboardSortedLinkedList implements SortedListInterface<Player> {

    // 其他代码...

    public boolean add(Player newEntry) {
        // 添加新玩家的代码...
    }

    // 其他方法...

    private class Node {

        private Player data;
        private Node next;

        private Node(Player data) {
            this.data = data;
            next = null;
        }

        private Node(Player data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}

然后,您可以在 testLeaderboard 类中添加玩家对象并按照他们的分数排序:

public class testLeaderboard {

   
    public static void main(String[] args) {
        SortedListInterface<Player> Player = new LeaderboardSortedLinkedList();
        
        Player.add(new Player("Player1", 1000000));
        Player.add(new Player("Player2", 500000));
        // 其他玩家的添加...
        
        System.out.printf("=================================\n" 
                         + "          Leaderboard\n"
                         +"=================================\n");
        
        for(int i=0; i < Player.size(); i++){
            Player currentPlayer = Player.get(i+1);
            System.out.printf("%3d. %s\n",(i+1), currentPlayer.getName() + " - " + currentPlayer.getPrize());
        }
        
    }
    
}

这样,您就可以在排行榜中同时使用玩家姓名和分数了。

英文:

I am trying to do a Leaderboard for a game by using a Sorted Linked List. I was able to do so by sorting the point in descending order which mean higher point to lower point. Moreover, I will also need to put player name together with the point. The problem comes here. The SLL(Sorted Linked List) I implemented is an Integer data type, it works perfectly with the Integer data type as it sorted the numbers.

SortedListInterface&lt;Integer&gt; Player = new LeaderboardSortedLinkedList&lt;Integer&gt;();

But when I trying to put the player name which used String, it won't be able to do so because the point data type will need to follow the player name's data type.
Below are the codes of the driver class:

public class testLeaderboard {

   
    public static void main(String[] args) {
        SortedListInterface&lt;Integer&gt; Player = new LeaderboardSortedLinkedList&lt;Integer&gt;();
        
            Player.add(1000000);
            Player.add(500000);
            Player.add(250000);
            Player.add(125000);
            Player.add(64000);
            Player.add(32000);
            Player.add(16000);
            Player.add(8000);
            Player.add(4000);
            Player.add(2000);
            Player.add(1000);
            Player.add(500);
            Player.add(300);
            Player.add(200);
            Player.add(100);
        
        
        System.out.printf(&quot;=================================\n&quot; 
                         + &quot;          Leaderboard\n&quot;
                         +&quot;=================================\n&quot;);
        
        for(int i=0; i&lt; Player.size();i++){
            
            System.out.printf(&quot;%3d. %s\n&quot;,(i+1), Player.get(i+1));
        }
        
    }
    
}

Here is the Entity class

public class Player {
    private String name;
    private int prize;

    public Player(String name, int prize) {
        this.name = name;
        this.prize = prize;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrize() {
        return prize;
    }

    public void setPrize(int prize) {
        this.prize = prize;
    }

    @Override
    public String toString() {
        return &quot;Player{&quot; + &quot;name=&quot; + name + &quot;, prize=&quot; + prize + &#39;}&#39;;
    }
}

Here's the custom Sorted Lineked List

public class LeaderboardSortedLinkedList&lt;T extends Comparable&lt;T&gt;&gt; implements SortedListInterface&lt;T&gt; {

    private Node firstNode;
    private int length;

    public LeaderboardSortedLinkedList() {
        firstNode = null;
        length = 0;
    }

    public boolean add(T newEntry) {
        Node newNode = new Node(newEntry);

        Node nodeBefore = null; 
        Node currentNode = firstNode;   
        while (currentNode != null &amp;&amp; newEntry.compareTo(currentNode.data) &lt; 0) {
            nodeBefore = currentNode;
            currentNode = currentNode.next;
        }

        if (isEmpty() || (nodeBefore == null)) { // CASE 1: add at beginning
            newNode.next = firstNode;
            firstNode = newNode;
        } else {	// CASE 2: add in the middle or at the end, i.e. after nodeBefore
            newNode.next = currentNode;
            nodeBefore.next = newNode;
        }
        length++;
        return true;
    }

    public boolean contains(T anEntry) {
        boolean found = false;
        Node tempNode = firstNode;
        int pos = 1;

        while (!found &amp;&amp; (tempNode != null)) {
            if (anEntry.compareTo(tempNode.data) &lt;= 0) {
                found = true;
            } else {
                tempNode = tempNode.next;
                pos++;
            }
        }
        if (tempNode != null &amp;&amp; tempNode.data.equals(anEntry)) {
            return true;
        } else {
            return false;
        }
    }

    public int size(){
         int count = 0;    
        //Node current will point to head    
        Node current = firstNode;    
            
        while(current != null) {    
            //Increment the count by 1 for each node    
            count++;    
            current = current.next;    
        }    
        return count;   
    }
    
     public T get(int position){
        T result = null;

    if ((position &gt;= 1) &amp;&amp; (position &lt;= length)) {
      Node currentNode = firstNode;
      for (int i = 0; i &lt; position - 1; ++i) {
        currentNode = currentNode.next;		// advance currentNode to next node
      }
      result = currentNode.data;	// currentNode is pointing to the node at givenPosition
    }

    return result;
    }
    
    
    public final void clear() {
        firstNode = null;
        length = 0;
    }

    public int getLength() {
        return length;
    }

    public boolean isEmpty() {
        return (length == 0);
    }

    
    public String toString() {
        String outputStr = &quot;&quot;;
        Node currentNode = firstNode;
        while (currentNode != null) {
            outputStr += currentNode.data + &quot;\n&quot;;;
            currentNode = currentNode.next;
        }
        return outputStr;
    }

    private class Node {

        private T data;
        private Node next;

        private Node(T data) {
            this.data = data;
            next = null;
        }

        private Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}

And the results is here

=================================
          Leaderboard
=================================
  1. 1000000
  2. 500000
  3. 250000
  4. 125000
  5. 64000
  6. 32000
  7. 16000
  8. 8000
  9. 4000
 10. 2000
 11. 1000
 12. 500
 13. 300
 14. 200
 15. 100

Here's my testing on the point with string data type because I can't think a way to use player name and point with 2 different data types at the same time in my custom ADT.

public class testLeaderboard {

   
    public static void main(String[] args) {
        SortedListInterface&lt;String&gt; Player = new LeaderboardSortedLinkedList&lt;String&gt;()
      
            Player.add(&quot;1000000&quot;);
            Player.add(&quot;500000&quot;);
            Player.add(&quot;250000&quot;);
            Player.add(&quot;125000&quot;);
            Player.add(&quot;64000&quot;);
            Player.add(&quot;32000&quot;);
            Player.add(&quot;16000&quot;);
            Player.add(&quot;8000&quot;);
            Player.add(&quot;4000&quot;);
            Player.add(&quot;2000&quot;);
            Player.add(&quot;1000&quot;);
            Player.add(&quot;500&quot;);
            Player.add(&quot;300&quot;);
            Player.add(&quot;200&quot;);
            Player.add(&quot;100&quot;);
            

    System.out.println(Player);
    }

And here's the result that it compare the first letter of the string.

8000
64000
500000
500
4000
32000
300
250000
2000
200
16000
125000
1000000
1000
100

Is there anyway to use both String and Integer in one ADT because if i couldn't do so, I won't be able sort the point. I'm so sorry for the long question. I am very new to data structures and algorithms so I really need some help on this. Much appreciate.

答案1

得分: 0

为了保持分数和名称的关联,您需要将Player对象整体添加到列表中,而不仅仅是它们的分数或名称:

SortedListInterface<Player> players = new LeaderboardSortedLinkedList<>();
 
players.add(new Player("Alpha", 1000000));
players.add(new Player("Beta", 500000));
players.add(new Player("Gamma", 250000));

为了使这个工作,您需要能够通过它们的分数对Player对象进行比较。您可以通过实现Comparable接口并添加一个compareTo方法来实现这一点。

您还应该添加一个toString()方法,以便您可以打印Player对象:

public class Player implements Comparable<Player> {
    private String name;
    private int prize;

    @Override
    public int compareTo(Player other) {
        return Integer.compare(this.prize, other.prize);
    }

    @Override
    public String toString() {
        return String.format("name='%s' prize=%d", name, prize);
    }
}
英文:

To keep the points and names together, you need to add Player objects into the list as they are, not just their points or their names:

SortedListInterface&lt;Player&gt; players = new LeaderboardSortedLinkedList&lt;&gt;();

players.add(new Player(&quot;Alpha&quot;, 1000000));
players.add(new Player(&quot;Beta&quot;, 500000));
players.add(new Player(&quot;Gamma&quot;, 250000));

For this to work, you will need to be able to compare Player objects by their point numbers. You do that by implementing the Comparable interface and adding a compareTo method.

You'll also want to add a toString() method, so that you can print a Player object.

public class Player implements Comparable&lt;Player&gt; {
    private String name;
    private int prize;

    @Override
    public int compareTo(Player other) {
        return Integer.compare(this.prize, other.prize);
    }

    @Override
    public String toString() {
        return String.format(&quot;name=&#39;%s&#39; prize=%d&quot;, name, prize);
    }
}

答案2

得分: 0

感谢您帮助我,我成功地获得了所需的输出。但是出现了一个小问题,就是这个:

=================================
           排行榜
=================================
  1. name='Alpha' prize=1000000
  2. name='Beta' prize=500000
  3. name='Gamma' prize=250000
构建成功(总时间:1秒)

它以这种方式打印输出 [name="Alpha"]。我不确定问题是什么,但我猜是我的 System.out.print 代码。

System.out.printf("%3d. %s\n",(i+1), players.get(i+1));

这里是我的 .get() 函数:

public T get(int position){
        T result = null;

    if ((position >= 1) && (position <= length)) {
      Node currentNode = firstNode;
      for (int i = 0; i < position - 1; ++i) {
        currentNode = currentNode.next;		// 将 currentNode 移动到下一个节点
      }
      result = currentNode.data;	// currentNode 指向给定位置的节点
    }

    return result;
}
英文:

Thank You for helping me I successfully get the output I want. But got a little problem which is this

=================================
           Leaderboard
=================================
  1. name=&#39;Alpha&#39; prize=1000000
  2. name=&#39;Beta&#39; prize=500000
  3. name=&#39;Gamma&#39; prize=250000
BUILD SUCCESSFUL (total time: 1 second)

It print the output at this way [name="Alpha"]. Im not sure what is the problem but i guess it's my System.out.print code.

System.out.printf(&quot;%3d. %s\n&quot;,(i+1), players.get(i+1));

and here's my .get() function.

  public T get(int position){
        T result = null;

    if ((position &gt;= 1) &amp;&amp; (position &lt;= length)) {
      Node currentNode = firstNode;
      for (int i = 0; i &lt; position - 1; ++i) {
        currentNode = currentNode.next;		// advance currentNode to next node
      }
      result = currentNode.data;	// currentNode is pointing to the node at givenPosition
    }

    return result;
    }

huangapple
  • 本文由 发表于 2020年8月19日 11:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63479380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定